question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
maximum-earnings-from-taxi
|
Easy Kotlin DP solution
|
easy-kotlin-dp-solution-by-user2962vm-kq52
|
\nfun maxTaxiEarnings(n: Int, rides: Array<IntArray>): Long {\n rides.sortBy{it[1]}\n \n val dp = Array(n+1){0.toLong()}\n var index
|
user2962vm
|
NORMAL
|
2022-03-11T07:42:23.475496+00:00
|
2022-03-11T23:42:16.159477+00:00
| 50 | false |
```\nfun maxTaxiEarnings(n: Int, rides: Array<IntArray>): Long {\n rides.sortBy{it[1]}\n \n val dp = Array(n+1){0.toLong()}\n var index = 0\n for (i in 1..n) {\n dp[i] = dp[i-1]\n \n while (index < rides.count() && rides[index][1] <= i) {\n dp[i] = Math.max(dp[i], dp[rides[index][0]] + (rides[index][1] - rides[index][0] + rides[index][2]))\n index++\n }\n }\n \n return dp[n]\n }\n```
| 1 | 0 |
[]
| 0 |
maximum-earnings-from-taxi
|
C++ | DP | O(n + rides.size())
|
c-dp-on-ridessize-by-arrohit258-fvxo
|
\nclass Solution {\npublic:\n long long maxTaxiEarnings(int n, vector<vector<int>>& rides) {\n vector<long long int>dp(n+1,0);\n vect
|
arrohit258
|
NORMAL
|
2022-02-01T11:13:55.996374+00:00
|
2022-02-01T11:14:26.682140+00:00
| 337 | false |
```\nclass Solution {\npublic:\n long long maxTaxiEarnings(int n, vector<vector<int>>& rides) {\n vector<long long int>dp(n+1,0);\n vector<vector<int>>end(n+1);\n int size=rides.size();\n for(int i=0;i<size;i++)\n end[rides[i][1]].push_back(i);\n for(int i=1;i<=n;i++){\n dp[i]=dp[i-1];\n if(end[i].size()==0)continue;\n for(auto e:end[i]){\n dp[i]=max(dp[i],rides[e][1]-rides[e][0]+rides[e][2]+dp[rides[e][0]]);\n }\n } \n return dp[n];\n }\n};\n```
| 1 | 0 |
[]
| 0 |
maximum-earnings-from-taxi
|
[Python]The most standard template for Binary Search
|
pythonthe-most-standard-template-for-bin-lxua
|
\nclass Solution:\n def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:\n \n\t\t# 3 types to write out standard binary search, that is,
|
surface09
|
NORMAL
|
2022-01-27T21:54:21.771272+00:00
|
2022-01-28T19:44:53.776160+00:00
| 311 | false |
```\nclass Solution:\n def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:\n \n\t\t# 3 types to write out standard binary search, that is, bisect_left, bisect, and (value + 1) - 1 (take the behind index) \n\t\t# All can be written out in details\n\t\t# This is for bisect_left\n def binary_search(target):\n \n left = 0\n right = m - 1\n\n while left + 1 < right:\n\n mid = left + (right - left) // 2\n\t\t\t\t\n\t\t\t\t# difference will happen here if it is bisect, not bisect_left\n if S[mid] < target:\n left = mid + 1\n else:\n right = mid\n\t\t\t\t\t\n\t\t\t# difference will happen here if it is bisect, not bisect_left\n if target <= S[left]:\n return left \n elif S[left] < target <= S[right]:\n return right \n else:\n return right + 1\n \n rides = sorted(rides)\n \n # S = [1, 3, 10, 11, 12, 13]\n S = [i[0] for i in rides]\n \n # m = 6\n m = len(rides)\n \n # dp = [0, 0, 0, 0, 0, 0, 0]\n dp = [0] * (m + 1)\n \n for k in range(m-1, -1, -1):\n \n idx = binary_search(rides[k][1])\n \n dp[k] = max(dp[k+1], rides[k][1] - rides[k][0] + rides[k][2] + dp[idx])\n \n\t\t# dp = [20, 20, 11, 9, 6, 6, 0]\n return dp[0]\n```
| 1 | 0 |
['Binary Tree', 'Python']
| 0 |
maximum-earnings-from-taxi
|
Java TreeMap easy solution
|
java-treemap-easy-solution-by-code_newbi-4ap7
|
\nclass Solution {\n public long maxTaxiEarnings(int n, int[][] rides) {\n Arrays.sort(rides, new Comparator<int[]>() {\n public int compar
|
code_newbie
|
NORMAL
|
2022-01-17T09:25:06.484409+00:00
|
2022-01-17T09:25:06.484451+00:00
| 340 | false |
```\nclass Solution {\n public long maxTaxiEarnings(int n, int[][] rides) {\n Arrays.sort(rides, new Comparator<int[]>() {\n public int compare(int[] ride1, int[] ride2) {\n if (ride1[1] == ride2[1]) {\n return ride1[0] - ride2[0];\n }\n return ride1[1] - ride2[1];\n }\n });\n TreeMap<Integer, Long> tm = new TreeMap<>();\n tm.put(0, 0l);\n for (int[] ride : rides) {\n if (ride[1] > n) {\n break;\n }\n long curr = tm.floorEntry(ride[0]).getValue() + ride[1] - ride[0] + ride[2];\n if (curr > tm.lastEntry().getValue()) {\n tm.put(ride[1], curr);\n }\n }\n return tm.lastEntry().getValue();\n }\n}\n```
| 1 | 0 |
['Tree', 'Java']
| 0 |
maximum-earnings-from-taxi
|
c++ | dp | Job scheduling variation | binary seaech
|
c-dp-job-scheduling-variation-binary-sea-tq7u
|
\nclass Solution {\npublic:\n long long maxTaxiEarnings(int n, vector<vector<int>>& rides) {\n for(auto&i:rides)i[2]+=(i[1]-i[0]);\n map<long l
|
srv-er
|
NORMAL
|
2022-01-04T02:39:02.588933+00:00
|
2022-01-04T02:39:02.588964+00:00
| 274 | false |
```\nclass Solution {\npublic:\n long long maxTaxiEarnings(int n, vector<vector<int>>& rides) {\n for(auto&i:rides)i[2]+=(i[1]-i[0]);\n map<long long,long long>mp;\n sort(rides.begin(),rides.end(),greater<vector<int>>());\n long long mx=0;\n for(auto& r:rides){\n auto j= mp.lower_bound(r[1]);\n long long v=j==mp.end()?0:j->second;\n mx=max(mx,r[2]+v);\n mp[r[0]]=mx;\n }\n return mx;\n }\n};\n```
| 1 | 0 |
['Dynamic Programming', 'C', 'Binary Tree']
| 1 |
maximum-earnings-from-taxi
|
Java Solution | Bottom-Up DP
|
java-solution-bottom-up-dp-by-fabulousdj-dopj
|
\nclass Solution {\n public long maxTaxiEarnings(int n, int[][] rides) {\n // sort by ride end\n Arrays.sort(rides, (r1, r2) -> Integer.compare
|
fabulousdj
|
NORMAL
|
2021-12-17T07:08:28.231925+00:00
|
2021-12-17T07:17:25.030544+00:00
| 283 | false |
```\nclass Solution {\n public long maxTaxiEarnings(int n, int[][] rides) {\n // sort by ride end\n Arrays.sort(rides, (r1, r2) -> Integer.compare(r1[1], r2[1]));\n int next = 0;\n long[] dp = new long[n+1];\n for (int i = 1; i < n+1; ++i) {\n dp[i] = dp[i-1];\n\t\t\t// iterate through rides with the same end\n while (next < rides.length && i == rides[next][1]) {\n var ride = rides[next];\n dp[i] = Math.max(dp[i], dp[ride[0]] + ride[1] - ride[0] + ride[2]);\n next++;\n } \n }\n return dp[n];\n }\n}\n```
| 1 | 0 |
[]
| 0 |
maximum-earnings-from-taxi
|
C++ || weighted job scheduling || Easy || detailed explanation with comments
|
c-weighted-job-scheduling-easy-detailed-xxie0
|
\n\nclass Solution {\npublic:\n long long maxTaxiEarnings(int n, vector<vector<int>>& rides) {\n // update cost in vector (as given tip + end -start)\n
|
Ajita_Mishra
|
NORMAL
|
2021-12-15T08:12:51.766714+00:00
|
2021-12-15T08:12:51.766749+00:00
| 423 | false |
\n```\nclass Solution {\npublic:\n long long maxTaxiEarnings(int n, vector<vector<int>>& rides) {\n // update cost in vector (as given tip + end -start)\n \n for(auto & x:rides)\n x[2]+=x[1]-x[0];\n \n // sort by start time in descending order\n \n sort(rides.begin(),rides.end(),greater<vector<int>>());\n \n map<long long int,long long int>dp;\n long long int maxP=0;\n \n for(auto ride:rides)\n {\n // check for given ride endtime check if there is any time greater than equal to present in map -> ex:- [13,18,1] already traversed when we check for ride [10,12,3] then we will get [13,18,1] in map similary we will check for possibilities\n auto j= dp.lower_bound(ride[1]); \n // in case there is no greater start time than our current endtime exists in map iterator will point to end in this case we will add zero profit else update with last ride profit\n long long int v= (j==dp.end())? 0: j->second;\n maxP=max(maxP,ride[2]+v);\n // update startime with max profit with rides uptill now it will help in next ride to decide whether can take the ride or not.\n dp[ride[0]]=maxP;\n \n }\n return maxP; \n }\n};\n```\n
| 1 | 0 |
['Dynamic Programming', 'C', 'Sorting', 'Binary Tree']
| 0 |
maximum-earnings-from-taxi
|
C# Top Down
|
c-top-down-by-clewby-opdd
|
\npublic class Solution {\n public long MaxTaxiEarnings(int n, int[][] rides) {\n Array.Sort(rides, (x,y) => x[0].CompareTo(y[0]));\n return ma
|
clewby
|
NORMAL
|
2021-12-02T08:27:53.422366+00:00
|
2021-12-02T08:27:53.422398+00:00
| 144 | false |
```\npublic class Solution {\n public long MaxTaxiEarnings(int n, int[][] rides) {\n Array.Sort(rides, (x,y) => x[0].CompareTo(y[0]));\n return max(0, rides, new long[rides.Length]);\n }\n \n private long max(int i, int[][] r, long[] memo)\n {\n if(i >= r.Length) return 0;\n if(memo[i] > 0) return memo[i];\n \n long profit = r[i][1]-r[i][0]+r[i][2];\n long sum = Math.Max(max(i+1, r, memo), profit);\n int next = search(i, r); \n sum = Math.Max(sum, max(next, r, memo) + profit);\n \n memo[i] = sum;\n return memo[i];\n }\n \n private int search(int i, int[][] r)\n {\n int lo = i, hi = r.Length;\n while(lo < hi)\n {\n int mid = lo+(hi-lo)/2;\n if(r[i][1] <= r[mid][0])\n hi = mid;\n else\n lo = mid+1;\n }\n return lo;\n }\n}\n```
| 1 | 0 |
[]
| 1 |
maximum-earnings-from-taxi
|
C++ || Binary search
|
c-binary-search-by-priyanka1230-y3qj
|
\n\npublic:\n static bool cmp(vector&v1,vector&v2)\n {\n return v1[1]<v2[1];\n }\n long long maxTaxiEarnings(int nn, vector>& rides) {\n
|
priyanka1230
|
NORMAL
|
2021-11-25T17:46:39.045408+00:00
|
2021-11-25T17:46:39.045443+00:00
| 236 | false |
```\n\n```public:\n static bool cmp(vector<int>&v1,vector<int>&v2)\n {\n return v1[1]<v2[1];\n }\n long long maxTaxiEarnings(int nn, vector<vector<int>>& rides) {\n vector<vector<int>>v;\n int n=rides.size();\n for(int i=0;i<rides.size();i++)\n {\n int x=rides[i][1]-rides[i][0]+rides[i][2];\n v.push_back({rides[i][0],rides[i][1],x});\n }\n sort(v.begin(),v.end(),cmp);\n vector<long long int>dp(n);\n dp[0]=v[0][2];\n for(int i=1;i<n;i++)\n {\n int idx=-1;\n int l=0;\n int r=i;\n while(l<=r)\n {\n int mid=(l+r)/2;\n if(v[mid][1]<=v[i][0])\n {\n idx=mid;\n l=mid+1;\n }\n else\n {\n r=mid-1;\n }\n }\n if(idx==-1)\n {\n dp[i]=max(dp[i-1],(long long)v[i][2]);\n }\n else\n {\n dp[i]=max(dp[i-1],dp[idx]+(long long)v[i][2]);\n }\n }\n return dp[n-1];\n }\n};
| 1 | 0 |
['Sorting', 'Binary Tree']
| 0 |
maximum-earnings-from-taxi
|
DP + Binary search C++ O(nlogn)
|
dp-binary-search-c-onlogn-by-sqld0ct0r-9o20
|
\nclass Solution {\npublic:\n static bool comp(vector<int>& a, vector<int>& b){\n return a[0] < b[0];\n }\n long long maxTaxiEarnings(int n, vec
|
sqld0ct0r
|
NORMAL
|
2021-11-20T11:07:02.011655+00:00
|
2021-11-20T11:07:02.011681+00:00
| 190 | false |
```\nclass Solution {\npublic:\n static bool comp(vector<int>& a, vector<int>& b){\n return a[0] < b[0];\n }\n long long maxTaxiEarnings(int n, vector<vector<int>>& A) {\n sort(A.begin(), A.end(), comp);\n vector<long long> dp(A.size());\n vector<int> t = A.back();\n dp[A.size()-1] = t[1] -t[0] + t[2];\n for(int i = A.size()-2; i >= 0; i--){\n vector<int> t = {A[i][1], INT_MIN};\n int j = upper_bound(A.begin() + i, A.end(), t) - A.begin();\n dp[i] = max(dp[i+1], (long long)A[i][1] - A[i][0] + A[i][2] + (j < A.size() ? dp[j]: 0));\n }\n \n return dp[0]; \n }\n};\n```
| 1 | 1 |
[]
| 0 |
maximum-earnings-from-taxi
|
Java, BinarySearch, O(mlogm)
|
java-binarysearch-omlogm-by-_jiraya-o8pp
|
\n public long maxTaxiEarnings(int n, int[][] rides) {\n Arrays.sort(rides, (r1, r2) -> r1[1] - r2[1]);\n \n List<long[]> preEnd = new A
|
_Jiraya
|
NORMAL
|
2021-11-12T11:20:38.099777+00:00
|
2021-11-12T11:20:38.099808+00:00
| 145 | false |
```\n public long maxTaxiEarnings(int n, int[][] rides) {\n Arrays.sort(rides, (r1, r2) -> r1[1] - r2[1]);\n \n List<long[]> preEnd = new ArrayList<>();\n preEnd.add(new long[]{0, 0});\n long ret = 0;\n for(int[] ride : rides) {\n long earn = ride[1] - ride[0] + ride[2];\n earn += bs(preEnd, ride[0]);\n ret = Math.max(ret, earn);\n if(earn > preEnd.get(preEnd.size() - 1)[1]) {\n preEnd.add(new long[]{ride[1], earn});\n }\n }\n return ret;\n }\n \n private long bs(List<long[]> pre, int limit) {\n int lo = 0;\n int hi = pre.size() - 1;\n int mid;\n while(lo <= hi) {\n mid = lo + ((hi - lo) >> 1);\n if(pre.get(mid)[0] <= limit) lo = mid + 1;\n else hi = mid - 1;\n }\n return pre.get(lo - 1)[1];\n }\n```
| 1 | 0 |
[]
| 0 |
maximum-earnings-from-taxi
|
O(N*logN) time, O(N) space. Priority Queue
|
onlogn-time-on-space-priority-queue-by-s-502r
|
The problem is similar to the Job Scheduling.\nWhen we have rides sorted by start we can iterate them from left to right and build chains of rides. For each rid
|
SmartBro
|
NORMAL
|
2021-11-11T13:28:08.027592+00:00
|
2021-11-11T13:31:21.102188+00:00
| 286 | false |
The problem is similar to the [Job Scheduling](https://leetcode.com/problems/maximum-profit-in-job-scheduling/).\nWhen we have `rides` sorted by `start` we can iterate them from left to right and build **chains** of rides. For each ride:\n* check if there are rides which were finished before current (they are in the MinPriorityQueue sorted by end time)\n\t* if there are rides which were already finished it means that it\'s safe to take them before current ride and there is no sense skipping them. we take the ride with the maximum earnings.\n* add current ride earnings to the priority queue, we need to keep track of its `end` and how much `earnings` we can get from that chain (the best chain earnings before current ride is `maxEarnings` + earnings from curent ride)\n\nNow let\'s calculate Time and Space complexity. We sort `O(N logN)` and then iterate `N` times with adding/removing items from PriorityQueue which takes `O(logN)`. Space for sorting depends on the language (avg. `O(logN)`), and our PriorityQueue can have all rides in the worst case when they all overlap.\nTime: `O(N*logN)`\nSpace: `O(N)`\n\n```javascript\nvar maxTaxiEarnings = function(n, rides) {\n rides.sort(([startA], [startB]) => startA - startB);\n const pq = new MinPriorityQueue({priority: ([end]) => end});\n let maxEarnings = 0;\n \n for (const [start, end, tip] of rides) {\n while (!pq.isEmpty() && start >= pq.front().element[0]) {\n const [_, earnings] = pq.dequeue().element;\n maxEarnings = Math.max(maxEarnings, earnings);\n }\n pq.enqueue([end, maxEarnings + end - start + tip]);\n }\n \n while (!pq.isEmpty()) {\n const [_, earnings] = pq.dequeue().element;\n maxEarnings = Math.max(maxEarnings, earnings);\n }\n \n return maxEarnings;\n};\n```
| 1 | 0 |
['Heap (Priority Queue)', 'JavaScript']
| 0 |
maximum-earnings-from-taxi
|
C++ || Sorting || Min Heap
|
c-sorting-min-heap-by-nikhilsvs-zj8r
|
define ll long long int\nclass Solution {\npublic:\n \n static bool sortByMe(vector &a,vector &b)\n {\n if(a[0] == b[0])\n {\n
|
nikhilsvs
|
NORMAL
|
2021-11-02T08:34:02.813706+00:00
|
2021-11-02T08:34:02.813751+00:00
| 233 | false |
#define ll long long int\nclass Solution {\npublic:\n \n static bool sortByMe(vector<int> &a,vector<int> &b)\n {\n if(a[0] == b[0])\n {\n return a[1] < b[1];\n }\n return a[0]<b[0];\n }\n long long maxTaxiEarnings(int n, vector<vector<int>>& rides) {\n \n priority_queue<pair<ll,ll>,vector<pair<ll,ll>>,greater<pair<ll,ll>>> pq;\n \n ll ans = 0;\n \n sort(rides.begin(),rides.end(),sortByMe);\n \n n = rides.size(); \n ll curr = 0;\n \n for(int i = 0;i<n;i++)\n {\n int st = rides[i][0];\n int et = rides[i][1];\n int tip = rides[i][2];\n \n \n while(!pq.empty() && pq.top().first <= st)\n {\n if(curr < pq.top().second)\n {\n curr = pq.top().second;\n }\n pq.pop();\n \n }\n \n ans = max(ans,et-st + tip + curr);\n \n pq.push({et,et-st + curr + tip});\n }\n \n return ans;\n }\n};
| 1 | 0 |
[]
| 0 |
maximum-earnings-from-taxi
|
Java Brute force, dp (3 approaches) 2 TLE 1 AC
|
java-brute-force-dp-3-approaches-2-tle-1-p4sh
|
Approach 1:\n\nbrute force(take the ride or not)(TLE)\n\nclass Solution {\n HashMap<Integer,List<int[]>> map = new HashMap();\n public long maxTaxiEarning
|
attackbyeren
|
NORMAL
|
2021-10-26T04:34:40.989923+00:00
|
2021-10-26T04:34:40.990002+00:00
| 156 | false |
Approach 1:\n\nbrute force(take the ride or not)(TLE)\n```\nclass Solution {\n HashMap<Integer,List<int[]>> map = new HashMap();\n public long maxTaxiEarnings(int n, int[][] rides) {\n create(n,rides);\n \n \n return f(1,n);\n }\n public long f(int start,int end){\n if(start==end)\n return 0;\n long max=0;\n for(int i=start;i<=end;i++){\n if(map.containsKey(i))\n for(int j=0;j<map.get(i).size();j++)\n max=Math.max(max,f(map.get(i).get(j)[1],end)+map.get(i).get(j)[0]);\n }\n return max;\n }\n public void create(int n,int rides[][]){\n for(int[] eachRide : rides)\n if(!map.containsKey(eachRide[0]))\n { List<int[]> myList =new ArrayList();\n myList.add(new int[]{eachRide[1]-eachRide[0]+eachRide[2],eachRide[1]});\n map.put(eachRide[0],myList);\n }\n else{\n List<int[]> myList =map.get(eachRide[0]);\n myList.add(new int[]{eachRide[1]-eachRide[0]+eachRide[2],eachRide[1]});\n }\n }\n}\n\n```\n\n\n\nApproach 2:(A better DP)(TLE)(can be optimized by priority queue**)\n```\nclass Solution {\n long []dp;\n \n public long maxTaxiEarnings(int n, int[][] rides) {\n \n Arrays.sort(rides,(a,b)->{\n return a[0]-b[0];\n });\n dp= new long[n+1];\n for(int[] each : rides){\n long value=dp[each[0]]+each[1]-each[0]+each[2];\n for(int i=each[1];i<=n;i++){\n dp[i]=Math.max(dp[i],value);\n \n }\n \n }\n return dp[n];\n }\n \n}`\n```\n\nApproach 3:(knapsack like appraoch taken from https://leetcode.com/problems/maximum-earnings-from-taxi/discuss/1470941/JavaC%2B%2BPython-DP-solution )\n\n```\nclass Solution {\n public long maxTaxiEarnings(int n, int[][] A) {\n Arrays.sort(A, (a, b) -> a[0] - b[0]);\n long[] dp = new long[n + 1];\n int j=0;\n for(int i=1;i<=n;i++){\n dp[i]=Math.max(dp[i],dp[i-1]);\n while(j<A.length && A[j][0]==i){\n dp[A[j][1]]=Math.max(dp[A[j][1]],dp[i]-A[j][0]+A[j][1]+A[j][2]);\n \n \n j++;\n }\n \n \n }\n return dp[n];\n \n }\n \n}\n```\n\ncomment down if you need any indepth explanation of any of these\n
| 1 | 0 |
['Dynamic Programming']
| 0 |
maximum-earnings-from-taxi
|
C++ | O(N*logN) | suffix array + binary search
|
c-onlogn-suffix-array-binary-search-by-s-8rie
|
\ntypedef long long ll;\nclass Solution {\npublic:\n long long maxTaxiEarnings(int n, vector<vector<int>>& rides) {\n vector<pair<ll, pair<ll, ll>>> i
|
samarjit
|
NORMAL
|
2021-10-08T18:28:59.466462+00:00
|
2021-10-08T18:28:59.466493+00:00
| 139 | false |
```\ntypedef long long ll;\nclass Solution {\npublic:\n long long maxTaxiEarnings(int n, vector<vector<int>>& rides) {\n vector<pair<ll, pair<ll, ll>>> intv;\n vector<ll> earn(rides.size());\n vector<ll> startTime;\n \n for(int i=0; i<rides.size(); i++){\n intv.push_back({rides[i][0], {rides[i][1], \n (ll)rides[i][2] + (ll)rides[i][1] - (ll)rides[i][0]}});\n startTime.push_back(rides[i][0]);\n }\n \n sort(intv.begin(), intv.end());\n sort(startTime.begin(), startTime.end());\n \n ll ret = 0;\n for(int i=intv.size()-1; i >= 0; i--){\n earn[i] = intv[i].second.second;\n \n // find k > i with start_point[k] > end_point[i] and maximum earning \n // for maximum earning maintain suffix array\n if(i+1 < intv.size()){\n int k = lower_bound(startTime.begin()+i+1, startTime.end(), intv[i].second.first) \n - startTime.begin();\n if(k < intv.size())\n earn[i] = max(earn[i], intv[i].second.second + earn[k]);\n }\n \n ret = max(ret, earn[i]);\n \n // suffix max computation\n if(i+1 < intv.size())\n earn[i] = max(earn[i], earn[i+1]);\n }\n \n return ret;\n }\n};\n```
| 1 | 0 |
[]
| 0 |
maximum-earnings-from-taxi
|
[C++] Recursion + Memoization
|
c-recursion-memoization-by-shady41-d5ib
|
\nclass Solution {\npublic:\n long long dp[30001];\n long long f(vector<vector<int>>&arr, long long i){\n if(i>=arr.size()) return 0;\n if(d
|
shady41
|
NORMAL
|
2021-09-28T15:55:27.741663+00:00
|
2021-10-17T12:30:56.061459+00:00
| 504 | false |
```\nclass Solution {\npublic:\n long long dp[30001];\n long long f(vector<vector<int>>&arr, long long i){\n if(i>=arr.size()) return 0;\n if(dp[i]!=-1) return dp[i];\n long long op1, op2;\n int l = i+1, r = arr.size()-1, m, j = -1;\n //if we chose to take this pasenger we can only pickup after he is dropped\n //so next eligible passenger can be searched\n while(l<=r){//binary search\n m = l + (r - l ) / 2;\n if(arr[m][0]>=arr[i][1]){\n j = m;\n r = m - 1;\n }\n else{\n l = m + 1;\n }\n }\n op1 = (arr[i][1]-arr[i][0]) + (arr[i][2]);//profit from current pasenger\n if(j != - 1)op1 += f(arr, j);//eligible may not exist\n op2 = f(arr, i+1);\n \n return dp[i] = max(op1, op2);\n }\n long long maxTaxiEarnings(int n, vector<vector<int>>&arr) {\n sort(arr.begin(), arr.end());\n memset(dp, -1, sizeof(dp));\n return f(arr, 0);\n }\n};\n```
| 1 | 0 |
['Recursion', 'Memoization', 'C']
| 0 |
maximum-earnings-from-taxi
|
[Swift] DP solution
|
swift-dp-solution-by-nyfa117-qn1e
|
\n func maxTaxiEarnings(_ n: Int, _ rides: [[Int]]) -> Int {\n var memo = Array(repeating: 0, count: n + 1)\n var ridesByEndpoint = [Int: [[Int
|
nyfa117
|
NORMAL
|
2021-09-26T15:51:17.491874+00:00
|
2021-09-26T15:52:37.709039+00:00
| 160 | false |
```\n func maxTaxiEarnings(_ n: Int, _ rides: [[Int]]) -> Int {\n var memo = Array(repeating: 0, count: n + 1)\n var ridesByEndpoint = [Int: [[Int]]]()\n \n for ride in rides {\n ridesByEndpoint[ride[1], default: []].append(ride)\n }\n \n for distance in 1...n {\n memo[distance] = memo[distance - 1]\n \n guard let rides = ridesByEndpoint[distance] else { continue }\n \n for i in 0..<rides.count {\n let ride = rides[i]\n let money = ride[1] - ride[0] + ride[2]\n \n memo[distance] = max(memo[ride[0]] + money, memo[distance])\n }\n }\n \n return memo.last!\n }\n```
| 1 | 0 |
['Dynamic Programming', 'Swift']
| 0 |
maximum-earnings-from-taxi
|
c++ O(n) dp solution adn O(nlgn) BIT Tree solution
|
c-on-dp-solution-adn-onlgn-bit-tree-solu-koet
|
O(n) dp solution \n\nclass Solution {\npublic: \n long long maxTaxiEarnings(int n, vector<vector<int>>& rides) {\n vector<vector<pair<int,int>>> tmp(
|
hanzhoutang
|
NORMAL
|
2021-09-25T05:28:26.143923+00:00
|
2021-09-25T05:28:26.143966+00:00
| 159 | false |
# O(n) dp solution \n```\nclass Solution {\npublic: \n long long maxTaxiEarnings(int n, vector<vector<int>>& rides) {\n vector<vector<pair<int,int>>> tmp(n+1);\n for(auto& r : rides) {\n tmp[r[1]].push_back({r[0], r[1] - r[0] + r[2]});\n } \n long long ret = 0; \n vector<long long> dp(n+1);\n for(int i = 1;i<=n;i++) {\n for(auto&& t : tmp[i]) {\n dp[i] = max(dp[i],dp[t.first] + t.second);\n }\n dp[i] = max(dp[i-1],dp[i]);\n }\n return dp.back();\n }\n};\n```\n\n# O(nlgn) bit tree solution \n``` \nclass Solution {\npublic:\n \n int lastOne(int x) {\n return x &(-x);\n }\n \n long long req(vector<long long>& bits, int i) {\n long long ret = 0;; \n for(;i;i-=lastOne(i)) {\n ret = max(ret,bits[i]);\n }\n return ret; \n }\n \n void update(vector<long long>& bits, int i, long long v) {\n for(;i<bits.size();i+=lastOne(i)) {\n bits[i] = max(bits[i],v);\n }\n }\n \n long long maxTaxiEarnings(int n, vector<vector<int>>& rides) {\n vector<long long> bits(n + 10);\n sort(rides.begin(),rides.end(),[](auto& a, auto& b) {\n return a[0] < b[0];\n });\n long long ret = 0; \n for(auto&& r : rides) {\n long long t = req(bits,r[0]);\n long long total_gain = t + r[1] - r[0] + r[2];\n update(bits,r[1],total_gain);\n ret = max(ret, total_gain);\n }\n return ret; \n }\n};\n```
| 1 | 0 |
[]
| 0 |
maximum-earnings-from-taxi
|
[Java] HashMap DP, no sorting
|
java-hashmap-dp-no-sorting-by-mav787-rmuu
|
dp[i] stores the intermediate result for index i.\n\n\nclass Solution {\n public long maxTaxiEarnings(int n, int[][] rides) {\n long[] dp = new long[n
|
mav787
|
NORMAL
|
2021-09-25T03:16:10.946943+00:00
|
2021-09-25T03:16:10.946972+00:00
| 122 | false |
dp[i] stores the intermediate result for index i.\n\n```\nclass Solution {\n public long maxTaxiEarnings(int n, int[][] rides) {\n long[] dp = new long[n + 1];\n \n Map<Integer, List<int[]>> map = new HashMap<>();\n \n for(int[] ride : rides){\n List<int[]> entry = map.getOrDefault(ride[1], new ArrayList<>());\n entry.add(ride);\n map.put(ride[1], entry);\n }\n \n \n for(int i = 1; i <= n; i++){\n\t\t\t// scenario 1: no rides taken. same as i - 1.\n dp[i] = dp[i - 1];\n \n\t\t\t// scenario 2: take a ride which ends at i\n if(map.containsKey(i)){\n for(int[] ride : map.get(i)){\n dp[i] = Math.max(dp[i], dp[ride[0]] + ride[1] - ride[0] + ride[2]);\n }\n }\n }\n \n return dp[n];\n }\n}\n\n```
| 1 | 0 |
[]
| 0 |
maximum-earnings-from-taxi
|
Lessons learned
|
lessons-learned-by-vyshnavkr-1b0g
|
Learning: \n Why sort on endTime: to decide if a taxi has to be picked, I need the info of all taxis that ended before the current taxi\'s startTime. (Think rea
|
vyshnavkr
|
NORMAL
|
2021-09-21T14:56:50.759968+00:00
|
2021-10-15T13:22:40.234242+00:00
| 136 | false |
**Learning**: \n* **Why sort on endTime**: to decide if a taxi has to be picked, I need the info of all taxis that ended before the current taxi\'s startTime. (Think real life). So **all taxis with endTime before current taxi\'s endTime must be computed already**. Thus the requirement of sort on endTime\n* **Why Binary Search or Linear Search**: (continuation of above) ... but what if current taxi started before its previous taxi (or previous taxis) ended. So those taxis will no longer be valid prev states of current taxi. Thus BS or LS to get the last valid prev state for current taxi.\n\n**Code**:\n```\n// Iterative approach. For recursive approach, read https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/1476877/Lessons-learned\nclass Solution {\n public long maxTaxiEarnings(int n, int[][] rides) {\n Arrays.sort(rides, (a, b) -> a[1] - b[1]);\n long[] dp = new long[rides.length];\n Arrays.fill(dp, -1);\n \n dp[0] = getCost(rides[0]);\n long ans = dp[0];\n for (int i = 1; i < rides.length; ++i) {\n \n int prevState = bs(rides, i);\n \n\t\t\t// IMP: Edge case 1\n long prevStateCachedVal = prevState == -1 ? 0 : dp[prevState];\n\t\t\t\n\t\t\t// IMP: Edge case 2. Never forget to max with dp[i - 1]. Reason being what if there is a better answer for i - 1 but is not a valid prev of i. Then for future taxis, if current taxi is a valid prev, then we need the dp[i - 1] value.\n // IMP: LIS doesn\'t have this. LIS has to scan all prev sates since search space is unsorted. Whlle here in Weighted Interval Scheduling search space is sorted. So for any current state, its first nearest valid prev state contains contribution of all the states behind this prev.\n dp[i] = Math.max(prevStateCachedVal + getCost(rides[i]), dp[i - 1]); \n\t\t\t\n ans = Math.max(ans, dp[i]);\n }\n \n return ans;\n }\n \n private long getCost(int[] ride) {\n int start = ride[0];\n int end = ride[1];\n int tip = ride[2];\n return end - start + tip;\n }\n \n private int bs(int[][] rides, int currentTaxi) {\n int start = 0, end = currentTaxi, nextIndex = -1;\n \n while (start <= end) {\n int mid = (start + end) / 2;\n if (rides[mid][1] <= rides[currentTaxi][0]) {\n nextIndex = mid;\n start = mid + 1;\n } else {\n end = mid - 1;\n }\n }\n return nextIndex;\n }\n}\n```
| 1 | 0 |
[]
| 1 |
maximum-earnings-from-taxi
|
[Scala] Bottom-up DP with pattern matching for understandability
|
scala-bottom-up-dp-with-pattern-matching-xz7b
|
\n def maxTaxiEarnings(n: Int, rides: Array[Array[Int]]): Long = {\n rides.sortInPlaceBy { case Array(_, end, _) => end }\n\n val dp = Array.ofDim[Long](
|
cosminci
|
NORMAL
|
2021-09-21T14:06:15.164550+00:00
|
2021-09-21T17:30:19.161241+00:00
| 91 | false |
```\n def maxTaxiEarnings(n: Int, rides: Array[Array[Int]]): Long = {\n rides.sortInPlaceBy { case Array(_, end, _) => end }\n\n val dp = Array.ofDim[Long](n + 1)\n var rideIdx = 0\n (1 to n).foreach { i =>\n while (rideIdx < rides.length && rides(rideIdx)(1) == i) {\n val Array(start, end, tip) = rides(rideIdx)\n dp(i) = math.max(dp(end), dp(start) + end - start + tip)\n rideIdx += 1\n }\n dp(i) = math.max(dp(i), dp(i - 1))\n }\n\n dp.last\n }\n```
| 1 | 0 |
['Dynamic Programming', 'Scala']
| 0 |
maximum-earnings-from-taxi
|
[Java] DP + Binary Search Solution with comments, TC: O(mlogm)
|
java-dp-binary-search-solution-with-comm-uugs
|
\n\npublic long maxTaxiEarnings(int n, int[][] rides) {\n //Time complexity: mlogm\n Arrays.sort(rides, (a, b) -> (a[1] - b[1]));//sort rides by t
|
seju_baek
|
NORMAL
|
2021-09-19T19:45:23.890746+00:00
|
2021-09-19T19:47:09.510877+00:00
| 80 | false |
\n```\npublic long maxTaxiEarnings(int n, int[][] rides) {\n //Time complexity: mlogm\n Arrays.sort(rides, (a, b) -> (a[1] - b[1]));//sort rides by their end time\n int m = rides.length;\n long[] dp = new long[m + 1];// dp[i]: the maximum dollars you can earn given rides [1, i];\n for (int i = 1; i <= m; i++) {\n int curProfit = rides[i - 1][1] - rides[i - 1][0] + rides[i - 1][2];\n int idx = bs(rides, 0, i - 1, rides[i - 1][0]);//find the largest index that its rides[idx][1] is smaller than or equal to target\n if (idx == -1) {//no non-overlapping rides before this ride\n dp[i] = Math.max(dp[i - 1], curProfit);\n } else {//either take the current passager or leave it\n dp[i] = Math.max(dp[i - 1], dp[idx + 1] + curProfit);\n }\n }\n return dp[m];\n }\n private int bs(int[][] arr, int l, int r, int target) {\n while (l <= r) {\n int mid = l + (r - l) / 2;\n if (arr[mid][1] <= target) {\n l = mid + 1; \n } else {\n r = mid - 1;\n }\n }\n return r;\n }\n```
| 1 | 0 |
[]
| 0 |
maximum-earnings-from-taxi
|
C++ recursive approach
|
c-recursive-approach-by-voldemorte-iyxt
|
For every passenger, we will have choice either to board him or not. If we board current passenger, then we will proceed to find next valid passenger and if we
|
voldemorte_
|
NORMAL
|
2021-09-19T02:21:47.601650+00:00
|
2021-09-19T02:24:22.462332+00:00
| 121 | false |
For every passenger, we will have choice either to board him or not. If we board current passenger, then we will proceed to find next valid passenger and if we don\'t board current passenger, we will go to next passenger.\n\n\nBelow is my implementation : \n```\nclass Solution {\npublic:\n long long solve(int i,vector<long long> &dp, vector<vector<int>>& rides, vector<long long> &nextStart)\n {\n if(i==rides.size()) return 0;\n if(dp[i]!=-1) return dp[i];\n\t\t\n // Finding next passenger if we board current passenger\n int ind=lower_bound(nextStart.begin(),nextStart.end(),rides[i][1])-nextStart.begin();\n \n return dp[i]=max(solve(ind,dp,rides,nextStart)+(long long)rides[i][2], solve(i+1,dp,rides,nextStart));\n }\n \n long long maxTaxiEarnings(int n, vector<vector<int>>& rides) {\n int size=rides.size();\n vector<long long> dp(size,-1),nextStart;\n \n sort(rides.begin(),rides.end());\n for(int i=0; i<rides.size(); i++)\n {\n rides[i][2]=rides[i][1]-rides[i][0]+rides[i][2];\n nextStart.push_back(rides[i][0]);\n }\n \n return solve(0,dp,rides,nextStart);\n }\n};\n```
| 1 | 0 |
[]
| 0 |
maximum-earnings-from-taxi
|
C++ | DP | Resemblance to other LC question
|
c-dp-resemblance-to-other-lc-question-by-kbhh
|
This question is pretty much same as https://leetcode.com/problems/maximum-profit-in-job-scheduling/. Here is my code to that problem:\nTime complexity O(n^2)\n
|
harshnadar23
|
NORMAL
|
2021-09-18T18:35:04.501483+00:00
|
2021-09-18T18:35:04.501530+00:00
| 198 | false |
This question is pretty much same as https://leetcode.com/problems/maximum-profit-in-job-scheduling/. Here is my code to that problem:\nTime complexity O(n^2)\n```\nclass Solution {\npublic:\n vector<vector<int> > job;\n map<int,int> dp;\n int n;\n \n int solve(int pos){\n if(pos>=n) return 0;\n\t\t\n if(dp.find(pos)!=dp.end()) return dp[pos];\n \n int next;\n for(next=pos+1;next<n;next++){\n if(job[next][0]>=job[pos][1]) break;\n }\n \n return dp[pos]= max(solve(pos+1), solve(next)+job[pos][2]);\n }\n \n int jobScheduling(vector<int>& start, vector<int>& end, vector<int>& profit) {\n n=profit.size();\n for(int i=0;i<n;i++){\n job.push_back({start[i], end[i], profit[i]});\n }\n sort(job.begin(), job.end());\n \n return solve(0);\n }\n};\n```\n\nNow lets come to this question. Firstly you can simply update the profit/tip to be (end-start+profit/tip). Here\'s my working code to this problem:\nHad to use binary search in this one, because the O(n^2) solution was giving TLE.\n```\nclass Solution {\npublic:\n vector<vector<int> > job;\n map<int,long long int> dp;\n int m;\n \n long long int solve(int pos){\n if(pos>=m) return 0;\n \n if(dp.find(pos)!=dp.end()) return dp[pos];\n \n \n int hi=m-1;\n int lo=pos+1;\n int next=hi+1;\n \n while(lo<=hi){\n int mid= lo+(hi-lo)/2;\n if(job[mid][0]>=job[pos][1]){\n next=mid;\n hi=mid-1;\n }\n else lo=mid+1;\n }\n \n // for(i=pos+1;i<m;i++){\n // if(job[i][0]>=job[pos][1]) break;\n // }\n return dp[pos]= max(solve(pos+1), solve(next)+job[pos][2]);\n }\n\n long long maxTaxiEarnings(int n, vector<vector<int>>& rides) {\n for(auto& it: rides){\n it[2]+=(it[1]-it[0]);\n }\n m=rides.size();\n sort(rides.begin(), rides.end());\n this->job = rides;\n return solve(0);\n }\n};\n```\nSee, same questions, just a bit change in language. \nKindly upvote!
| 1 | 1 |
['Dynamic Programming', 'C', 'Binary Tree']
| 0 |
maximum-earnings-from-taxi
|
C++ | TOP DOWN DP | BINARY SEARCH
|
c-top-down-dp-binary-search-by-ss768869-pr4a
|
class Solution {\npublic:\n vector dp ; \n \n \n long long helper(int i , vector> &rides )\n {\n if(i==rides.size())\n return 0 ;\
|
ss768869
|
NORMAL
|
2021-09-18T16:44:54.260594+00:00
|
2021-09-18T16:44:54.260624+00:00
| 158 | false |
class Solution {\npublic:\n vector<long long> dp ; \n \n \n long long helper(int i , vector<vector<int>> &rides )\n {\n if(i==rides.size())\n return 0 ;\n \n if(dp[i]!=-1)\n return dp[i] ;\n \n int s = i+1 , e = rides.size() -1 ;\n int ans = -1; \n \n while(s<=e)\n {\n int mid = (s+e)/2 ;\n \n if(rides[mid][0] >= rides[i][1])\n {\n ans = mid ;\n e=mid-1;\n }\n else\n s = mid+1 ; \n \n }\n \n \n long long ans1 = rides[i][1] - rides[i][0] + rides[i][2] ;\n \n if(ans != -1)\n ans1 += helper(ans , rides); \n \n \n return dp[i] = max(ans1 , helper(i+1 , rides )) ; \n \n }\n long long maxTaxiEarnings(int n, vector<vector<int>>& rides) {\n \n \n sort(rides.begin() , rides.end()) ;\n \n dp.resize(rides.size() , -1) ;\n \n return helper(0 , rides ) ; \n \n }\n};
| 1 | 0 |
[]
| 0 |
maximum-earnings-from-taxi
|
Java: DP O(n+m)
|
java-dp-onm-by-prezes-rolk
|
Firstly, note we can sort rides by the starting point to use in DP and achieve O(n+mlogm) time complexity:\n\nstatic int START= 0, END= 1, TIP= 2;\npublic long
|
prezes
|
NORMAL
|
2021-09-18T16:35:55.173381+00:00
|
2021-09-18T20:18:15.657498+00:00
| 211 | false |
Firstly, note we can sort rides by the starting point to use in DP and achieve O(n+mlogm) time complexity:\n```\nstatic int START= 0, END= 1, TIP= 2;\npublic long maxTaxiEarnings(int n, int[][] rides) {\n\tint m= rides.length;\n\tArrays.sort(rides, (r1, r2)->r1[START]-r2[START]);\n\tlong[] dp= new long[n+1]; \n\tfor(int i=1, j=0; i<=n; i++){\n\t\tdp[i]= Math.max(dp[i-1], dp[i]);\n\t\t// consider all rides starting at i i.e. rides[j][0]==i \n\t\tfor(; j<m; j++){\n\t\t\tint start= rides[j][START], end= rides[j][END], tip= rides[j][TIP];\n\t\t\tif(start!=i) break;\n\t\t\tdp[end]= Math.max(dp[end], dp[start]+end-start+tip);\n\t\t}\n\t}\n\treturn dp[n];\n}\n```\nThe order of processing rides matters only as far as the starting point though - so instead of full O(mlogm) sort, we can bucket rides by their starting point to achieve the overall **O(n+m)** time complexity:\n```\nstatic int START= 0, END= 1, TIP= 2; \npublic long maxTaxiEarnings(int n, int[][] rides) {\n\t// bucket rides by pick up point in O(m)\n\tArrayList<int[]>[] rideBuckets= new ArrayList[n+1];\n\tfor(int[] ride:rides){\n\t\tArrayList<int[]> bucket= rideBuckets[ride[START]];\n\t\tif(bucket==null) bucket= rideBuckets[ride[START]]= new ArrayList<>();\n\t\tbucket.add(ride);\n\t}\n\t// consider all rides starting at i i.e. ride[START]==i in O(n+m)\n\tlong[] dp= new long[n+1];\n\tfor(int i=1; i<=n; i++){\n\t\tdp[i]= Math.max(dp[i-1], dp[i]);\n\t\tif(rideBuckets[i]!=null)\n\t\tfor(int[] ride:rideBuckets[i]){\n\t\t\tint start= ride[START], end= ride[END], tip= ride[TIP];\n\t\t\tdp[end]= Math.max(dp[end], dp[start]+end-start+tip);\n\t\t}\n\t}\n\treturn dp[n];\n}\n```
| 1 | 0 |
[]
| 0 |
maximum-earnings-from-taxi
|
Simple DP with Explanation || C++ Code
|
simple-dp-with-explanation-c-code-by-gan-uq7c
|
dp[i] stores the max earning if we start from i.\nSay we have n people want to go from point i to any other point > i.\nNow we have two options -\ni) We take an
|
ganapati_biswas
|
NORMAL
|
2021-09-18T16:17:53.307995+00:00
|
2021-09-18T16:26:29.361403+00:00
| 94 | false |
**dp[i]** stores the max earning if we start from i.\nSay we have n people want to go from point i to any other point > i.\nNow we have two options -\ni) We take any of the passenger from point i.\nii) We don\'t take any passenger.\n\nIf we take jth passenger then dp[i] will be \n**dp[i]= end point of jth passenger - start point of jth passenger + tip given by the jth passenger + dp[end point of jth passenger]**\n```\n#define ll long long int \nclass Solution {\npublic:\n long long maxTaxiEarnings(int n, vector<vector<int>>& rides) {\n vector<ll> dp(n+1,0);\n unordered_map<ll,vector<vector<ll>>> startTime;\n \n for(auto x: rides)\n {\n ll start=x[0];\n ll end=x[1];\n ll tip=x[2];\n \n startTime[start].push_back({end,tip});\n }\n \n for(int i=n-1;i>=1;i--)\n {\n dp[i]=dp[i+1];\n if(startTime[i].size()==0)continue;\n for(auto x: startTime[i])\n {\n ll end=x[0];\n ll tip=x[1];\n \n dp[i]=max(dp[i],end-i+tip+dp[end]);\n }\n }\n \n \n return dp[1];\n }\n};\n```
| 1 | 0 |
[]
| 0 |
maximum-earnings-from-taxi
|
Python | Heapq | Simple And Efficient Solution
|
python-heapq-simple-and-efficient-soluti-amuf
|
\nclass Solution:\n def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:\n rides.sort(key=lambda x: x[0])\n heap = []\n max
|
akash3anup
|
NORMAL
|
2021-09-18T16:14:09.379868+00:00
|
2021-09-18T16:14:09.379898+00:00
| 113 | false |
```\nclass Solution:\n def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:\n rides.sort(key=lambda x: x[0])\n heap = []\n maxProfit = 0\n currentProfit = 0\n for ride in rides:\n\t\t\t# Calculate the total profit of all the rides that would have end by this time(start: startTime of current ride)\n while heap and heap[0][0] <= ride[0]:\n _, tempProfit = heapq.heappop(heap)\n currentProfit = max(currentProfit, tempProfit)\n\t\t\t# Push the ride into heap to use it further. It\'s profit would be definitely currentProfit + profit(of current ride)\n heapq.heappush(heap, [ride[1], currentProfit + ride[1] - ride[0] + ride[2]])\n maxProfit = max(maxProfit, currentProfit + ride[1] - ride[0] + ride[2])\n return maxProfit\n```\n\n***If you liked the above solution then please upvote!***
| 1 | 0 |
[]
| 0 |
reorder-list
|
[Python] 3 steps to success, explained
|
python-3-steps-to-success-explained-by-d-khb4
|
If you never solved singly linked lists problems before, or you do not have a lot of experience, this problem can be quite difficult. However if you already kno
|
dbabichev
|
NORMAL
|
2020-08-20T08:27:52.945548+00:00
|
2020-08-20T08:27:52.945584+00:00
| 45,812 | false |
If you never solved singly linked lists problems before, or you do not have a lot of experience, this problem can be quite difficult. However if you already know all the tricks, it is not difficult at all. Let us first try to understand what we need to do. For list `[1,2,3,4,5,6,7]` we need to return `[1,7,2,6,3,5,4]`. We can note, that it is actually two lists `[1,2,3,4]` and `[7,6,5]`, where elements are interchange. So, to succeed we need to do the following steps:\n1. Find the middle of or list - be careful, it needs to work properly both for even and for odd number of nodes. For this we can either just count number of elements and then divide it by to, and do two traversals of list. Or we can use `slow/fast` iterators trick, where `slow` moves with speed `1` and `fast` moves with speed `2`. Then when `fast` reches the end, `slow` will be in the middle, as we need.\n2. Reverse the second part of linked list. Again, if you never done it before, it can be quite painful, please read oficial solution to problem **206. Reverse Linked List**. The idea is to keep **three** pointers: `prev, curr, nextt` stand for previous, current and next and change connections in place. Do not forget to use `slow.next = None`, in opposite case you will have list with loop.\n3. Finally, we need to merge two lists, given its heads. These heads are denoted by `head` and `prev`, so for simplisity I created `head1` and `head2` variables. What we need to do now is to interchange nodes: we put `head2` as next element of `head1` and then say that `head1` is now `head2` and `head2` is previous `head1.next`. In this way we do one step for one of the lists and rename lists, so next time we will take element from `head2`, then rename again and so on.\n\n**Complexity**: Time complexity is `O(n)`, because we first do `O(n)` iterations to find middle, then we do `O(n)` iterations to reverse second half and finally we do `O(n)` iterations to merge lists. Space complexity is `O(1)`.\n\n```\nclass Solution:\n def reorderList(self, head):\n #step 1: find middle\n if not head: return []\n slow, fast = head, head\n while fast.next and fast.next.next:\n slow = slow.next\n fast = fast.next.next\n \n #step 2: reverse second half\n prev, curr = None, slow.next\n while curr:\n nextt = curr.next\n curr.next = prev\n prev = curr\n curr = nextt \n slow.next = None\n \n #step 3: merge lists\n head1, head2 = head, prev\n while head2:\n nextt = head1.next\n head1.next = head2\n head1 = head2\n head2 = nextt\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!**
| 750 | 6 |
['Two Pointers']
| 31 |
reorder-list
|
Java solution with 3 steps
|
java-solution-with-3-steps-by-wanqing-99pu
|
This question is a combination of Reverse a linked list I & II. It should be pretty straight forward to do it in 3 steps :)\n\n public void reorderList(ListN
|
wanqing
|
NORMAL
|
2015-05-13T21:31:52+00:00
|
2018-10-14T20:24:01.475368+00:00
| 136,733 | false |
This question is a combination of **Reverse a linked list I & II**. It should be pretty straight forward to do it in 3 steps :)\n\n public void reorderList(ListNode head) {\n if(head==null||head.next==null) return;\n \n //Find the middle of the list\n ListNode p1=head;\n ListNode p2=head;\n while(p2.next!=null&&p2.next.next!=null){ \n p1=p1.next;\n p2=p2.next.next;\n }\n \n //Reverse the half after middle 1->2->3->4->5->6 to 1->2->3->6->5->4\n ListNode preMiddle=p1;\n ListNode preCurrent=p1.next;\n while(preCurrent.next!=null){\n ListNode current=preCurrent.next;\n preCurrent.next=current.next;\n current.next=preMiddle.next;\n preMiddle.next=current;\n }\n \n //Start reorder one by one 1->2->3->6->5->4 to 1->6->2->5->3->4\n p1=head;\n p2=preMiddle.next;\n while(p1!=preMiddle){\n preMiddle.next=p2.next;\n p2.next=p1.next;\n p1.next=p2;\n p1=p2.next;\n p2=preMiddle.next;\n }\n }
| 639 | 17 |
['Java']
| 78 |
reorder-list
|
C++ really simple solution using stack, with explanations
|
c-really-simple-solution-using-stack-wit-jj28
|
Like it? Please upvote...\n\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n if ((!head) || (!head->next) || (!head->next->next)) ret
|
yehudisk
|
NORMAL
|
2020-08-20T11:40:41.710233+00:00
|
2020-08-20T12:00:52.584983+00:00
| 36,094 | false |
**Like it? Please upvote...**\n```\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n if ((!head) || (!head->next) || (!head->next->next)) return; // Edge cases\n \n stack<ListNode*> my_stack;\n ListNode* ptr = head;\n int size = 0;\n while (ptr != NULL) // Put all nodes in stack\n {\n my_stack.push(ptr);\n size++;\n ptr = ptr->next;\n }\n \n ListNode* pptr = head;\n for (int j=0; j<size/2; j++) // Between every two nodes insert the one in the top of the stack\n {\n ListNode *element = my_stack.top();\n my_stack.pop();\n element->next = pptr->next;\n pptr->next = element;\n pptr = pptr->next->next;\n }\n pptr->next = NULL;\n }\n};\n```
| 488 | 5 |
['Stack', 'C']
| 33 |
reorder-list
|
Java solution with 3 steps
|
java-solution-with-3-steps-by-jeantimex-7alr
|
public class Solution {\n \n public void reorderList(ListNode head) {\n if (head == null || head.next == null)\n return;\n
|
jeantimex
|
NORMAL
|
2015-07-08T00:21:48+00:00
|
2018-10-21T17:04:29.240967+00:00
| 37,760 | false |
public class Solution {\n \n public void reorderList(ListNode head) {\n if (head == null || head.next == null)\n return;\n \n // step 1. cut the list to two halves\n // prev will be the tail of 1st half\n // slow will be the head of 2nd half\n ListNode prev = null, slow = head, fast = head, l1 = head;\n \n while (fast != null && fast.next != null) {\n prev = slow;\n slow = slow.next;\n fast = fast.next.next;\n }\n \n prev.next = null;\n \n // step 2. reverse the 2nd half\n ListNode l2 = reverse(slow);\n \n // step 3. merge the two halves\n merge(l1, l2);\n }\n \n ListNode reverse(ListNode head) {\n ListNode prev = null, curr = head, next = null;\n \n while (curr != null) {\n next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n \n return prev;\n }\n \n void merge(ListNode l1, ListNode l2) {\n while (l1 != null) {\n ListNode n1 = l1.next, n2 = l2.next;\n l1.next = l2;\n \n if (n1 == null)\n break;\n \n l2.next = n1;\n l1 = n1;\n l2 = n2;\n }\n }\n \n }
| 395 | 2 |
['Java']
| 24 |
reorder-list
|
C++ EASY TO SOLVE || Beginner Friendly with detailed explanation and dry run
|
c-easy-to-solve-beginner-friendly-with-d-5ups
|
Intuition:-\nAfter reading the question we got the gist that we need to reform the linkedlist in the manner such as\nfirstnode->lastnode->secondnode->penultimat
|
Cosmic_Phantom
|
NORMAL
|
2021-12-22T03:18:25.790072+00:00
|
2024-08-23T02:33:45.216185+00:00
| 25,896 | false |
**Intuition:-**\nAfter reading the question we got the gist that we need to reform the linkedlist in the manner such as\n`firstnode->lastnode->secondnode->penultimate node->third node->3rd last node ............` .\nSo there are two ways that comes to my mind while thinking about a approach . Those are ,\n\n**1. Brute Force :-**\n* In this we will first traverse to penultimate node and then start relinking each node .\n\n**2.** **Two pointer approach[sometimes referred as Tortoise and hare method]:-**\n* We will have two pointers 1st pointer moving at speed of 1node and 2nd pointer moving at speed of twice the node. So basically one is moving at double speed and thus when it will be finished, the other has to be midway) and possibly adjusting it with lists of even length. This creates two halfs of linkedlist\n* Then we reverse the second list and Finally we merge these two lists.\n\n**Brute-Force Algorithm:-**\n1. First some base cases that we need to take care i.e if the linked list has zero,one or two elements just return it \n2. Now next we need to find the penultimate node, so after finding it we can start the relinking process\n3. Now start the relinking process as 1st node with last node ,2nd node with penultimate node, 3rd node with 3rd last node ......\n4. Now repeat 2nd and 3rd steps.\n\n**Let\'s have a dy run before starting the code:-**\n\n\n\n**Brute-Force code-:**\n```\n//Upvote and Comment\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n //base case i.e if the linked list has zero,one or two elments just return it\n if(!head || !head->next || !head->next->next) return;\n \n //Find the penultimate node i.e second last node of the linkedlist\n ListNode* penultimate = head;\n while (penultimate->next->next) penultimate = penultimate->next;\n \n // Link the penultimate with the second element\n penultimate->next->next = head->next;\n head->next = penultimate->next;\n \n //Again set the penultimate to the the last \n penultimate->next = NULL;\n \n // Do the above steps rcursive\n reorderList(head->next->next);\n }\n};\n```\n.\n\n\n**Two pointer Approach [Tortoise and Hare method]:-**\n*This approach is much faster and efficient in terms of Time and Space Complexity the only drawback is that it looks a little bit lengthy but trust me it\'s easy to understand*.\n\n**Two pointer Approach Algorithm:**\n1. First let\'s take two pointers name it as `half` and `temp` . `temp ` is faster than `half` by 1. \n2. When `temp` reaches the end of linkedlsit `half` reaches the middle element .So this is how the linkedlist will get divided in two halfes as the center will become a dividing node .\n3. Now reverse the second half . \n4. After reversing the second half, merge the first half and second half\n\n**Let\'s have a dy run before starting the code:-**\nLet\'s take the same example as above:\n```\nLinked list:[1,2,3,4,5]\n* search for the central element, which will be three in our case\n* split the list in two halfes that will be [1,2,3] and [4,5]\n* Now reverse the second half that will be [5,4]\n* Now merge both the halfes \n[1,2,3]\n\t[5,4]\n=>[1,5,2,4,3]\n\n**See told you it\'s easy to understand**\n```\n\n\n**Two pointer Approach Code:-**\n```\n//Upvote and Comment\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n // base case : linkedlist is empty\n if (!head) return;\n \n // finding the middle with the help of two pointer approach\n ListNode *tmp = head, *half = head, *prev = NULL;\n while (tmp->next && tmp->next->next) {\n tmp = tmp->next->next;\n half = half->next;\n }\n \n // adding one bit in case of lists with even length\n if (tmp->next) half = half->next;\n \n // Now reverse the second half\n while (half) {\n tmp = half->next;\n half->next = prev;\n prev = half;\n half = tmp;\n }\n half = prev;\n \n // After reversing the second half, let\'s merge both the halfes\n while (head && half) {\n tmp = head->next;\n prev = half->next;\n head->next = half;\n half->next = tmp;\n head = tmp;\n half = prev;\n }\n \n // Base case : closing when we had even length arrays\n if (head && head->next) head->next->next = NULL;\n }\n};\n```\n**Time Complexity :** *`O(N) [ O(N) to find mid of list, O(N/2) to reverse the 2nd half and in the end O(N) for relinking purpose ]`*\n**Space Complexity :** *`O(1) [intermediate state variables are the only thing that we used]`*\n\n***\n\n
| 228 | 19 |
['Linked List', 'Two Pointers', 'Recursion', 'C', 'C++']
| 11 |
reorder-list
|
A concise O(n) time, O(1) in place solution
|
a-concise-on-time-o1-in-place-solution-b-badx
|
// O(N) time, O(1) space in total\n void reorderList(ListNode *head) {\n if (!head || !head->next) return;\n \n // find the middle node:
|
shichaotan
|
NORMAL
|
2015-01-16T06:23:37+00:00
|
2018-10-26T01:55:02.762497+00:00
| 48,566 | false |
// O(N) time, O(1) space in total\n void reorderList(ListNode *head) {\n if (!head || !head->next) return;\n \n // find the middle node: O(n)\n ListNode *p1 = head, *p2 = head->next;\n while (p2 && p2->next) {\n p1 = p1->next;\n p2 = p2->next->next;\n }\n \n // cut from the middle and reverse the second half: O(n)\n ListNode *head2 = p1->next;\n p1->next = NULL;\n \n p2 = head2->next;\n head2->next = NULL;\n while (p2) {\n p1 = p2->next;\n p2->next = head2;\n head2 = p2;\n p2 = p1;\n }\n \n // merge two lists: O(n)\n for (p1 = head, p2 = head2; p1; ) {\n auto t = p1->next;\n p1 = p1->next = p2;\n p2 = t;\n }\n \n //for (p1 = head, p2 = head2; p2; ) {\n // auto t = p1->next;\n // p1->next = p2;\n // p2 = p2->next;\n // p1 = p1->next->next = t;\n //}\n }
| 215 | 2 |
[]
| 19 |
reorder-list
|
Python O(n) by two-pointers [w/ Visualization]
|
python-on-by-two-pointers-w-visualizatio-qfgg
|
The first method is to reorder by two pointers with the help of aux O(n) space array.\n\nThe second method is to reorder by mid-point finding, linked list rever
|
brianchiang_tw
|
NORMAL
|
2020-08-20T09:39:23.907885+00:00
|
2020-08-20T09:39:23.907915+00:00
| 18,697 | false |
The first method is to reorder by **two pointers** with the help of **aux O(n)** space **array**.\n\nThe second method is to reorder by **mid-point finding**, **linked list reverse**, and **linkage update** in O(1) aux space.\n\n---\n\nMethod_#1\n\n**Visualization and Diagram**\n\n\n\n---\n\n**Implementation**:\n\n```\nclass Solution:\n def reorderList(self, head: ListNode) -> None:\n """\n Do not return anything, modify head in-place instead.\n """\n\t\t\n\t\t# ----------------------------------------------\n\t\t# Save linked list in array\n\t\t\n arr = []\n \n cur, length = head, 0\n\t\t\n while cur:\n arr.append( cur )\n cur, length = cur.next, length + 1\n \n\t\t# ----------------------------------------------\n # Reorder with two-pointers\n\t\t\n left, right = 0, length-1\n last = head\n \n while left < right:\n arr[left].next = arr[right]\n left += 1\n \n if left == right: \n last = arr[right]\n break\n \n arr[right].next = arr[left]\n right -= 1\n \n last = arr[left]\n \n if last:\n last.next= None\n```\n\n---\n\nMethod_#2\n\n**Visualization and Diagram**\n\n\n\n---\n\n\n\n---\n\n\n\n\n---\n\n**Implementation**:\n\n```\nclass Solution:\n def reorderList(self, head: ListNode) -> None:\n """\n Do not return anything, modify head in-place instead.\n """\n \n if not head:\n # Quick response for empty linked list\n return None\n \n # ------------------------------------------\n # Locate the mid point of linked list\n # First half is the linked list before mid point\n # Second half is the linked list after mid point\n \n fast, slow = head, head\n \n while fast and fast.next:\n slow, fast = slow.next, fast.next.next\n \n mid = slow\n \n # ------------------------------------------\n # Reverse second half\n \n prev, cur = None, mid\n \n while cur:\n cur.next, prev, cur = prev, cur, cur.next\n \n head_of_second_rev = prev\n \n # ------------------------------------------\n # Update link between first half and reversed second half\n \n first, second = head, head_of_second_rev\n \n while second.next:\n \n next_hop = first.next\n first.next = second\n first = next_hop\n \n next_hop = second.next\n second.next = first\n second = next_hop\n```\n\n---
| 170 | 1 |
['Linked List', 'Two Pointers', 'Iterator', 'Python', 'Python3']
| 20 |
reorder-list
|
A python solution O(n) time, O(1) space
|
a-python-solution-on-time-o1-space-by-ri-uh6l
|
\n\n # Splits in place a list in two halves, the first half is >= in size than the second.\n # @return A tuple containing the heads of the two halves\n
|
riccardo
|
NORMAL
|
2014-09-14T14:54:59+00:00
|
2018-10-22T21:03:52.381996+00:00
| 31,615 | false |
\n\n # Splits in place a list in two halves, the first half is >= in size than the second.\n # @return A tuple containing the heads of the two halves\n def _splitList(head):\n fast = head\n slow = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next\n fast = fast.next\n \n middle = slow.next\n slow.next = None\n \n return head, middle\n \n # Reverses in place a list.\n # @return Returns the head of the new reversed list\n def _reverseList(head):\n \n last = None\n currentNode = head\n \n while currentNode:\n nextNode = currentNode.next\n currentNode.next = last\n last = currentNode\n currentNode = nextNode\n \n return last\n \n # Merges in place two lists\n # @return The newly merged list.\n def _mergeLists(a, b):\n \n tail = a\n head = a\n \n a = a.next\n while b:\n tail.next = b\n tail = tail.next\n b = b.next\n if a:\n a, b = b, a\n \n return head\n \n \n class Solution:\n \n # @param head, a ListNode\n # @return nothing\n def reorderList(self, head):\n \n if not head or not head.next:\n return\n \n a, b = _splitList(head)\n b = _reverseList(b)\n head = _mergeLists(a, b)
| 131 | 3 |
['Linked List', 'Python']
| 12 |
reorder-list
|
✅ [C++/Python] Simple Solutions w/ Explanation | 2-Pointers O(N) & Inplace O(1) Space Approaches
|
cpython-simple-solutions-w-explanation-2-taw1
|
We are given a list which we need to re-order in alternate fashion like L1 -> Ln-1 -> L2 -> Ln-2...\n\n---\n\n\u2714\uFE0F Solution - I (2-Pointers using Extra
|
archit91
|
NORMAL
|
2021-12-22T08:08:34.184487+00:00
|
2021-12-22T14:22:59.269624+00:00
| 9,335 | false |
We are given a list which we need to re-order in alternate fashion like `L1 -> Ln-1 -> L2 -> Ln-2...`\n\n---\n\n\u2714\uFE0F ***Solution - I (2-Pointers using Extra Space)***\n\nWe can solve this question easily if using extra space is allowed. The re-ordering arrangement basically consist of 1st node, then last node, then 2nd node, then 2nd last node and so on till all nodes are covered. Thus, we just put one node from the start, then one from end in an alternating fashion. In this approach - \n\n* We first use an auxillary array to store the nodes of linked-list\n* Once the array is filled, we initialize two variables `L` and `R` which denotes the current positions on the two ends from which we need to re-order the list in alternate fashion\n* In odd iteration, we assign the next node as `arr[L]` and move the `L` pointer ahead\n* In even iteration, we assign the next node as `arr[R]` and move the `R` pointer backward\n* This will re-order the list as alternating nodes from start and end as required.\n\n**C++**\n```cpp\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n vector<ListNode*> arr;\n for(auto iter = head; iter; iter = iter -> next)\n arr.push_back(iter);\n \n\t\t// pointers to start and end of list. Re-order in alternating fashion from both end\n int L = 1, R = size(arr)-1;\n for(int i = 0; i < size(arr); i++, head = head -> next) \n if(i & 1) // odd iteration:\n head -> next = arr[L++]; // - pick node from L & update L ptr\n else // even iteration\n head -> next = arr[R--]; // - pick node from R & update R ptr\n \n head -> next = nullptr;\n }\n};\n```\n\n**Python**\n```python\nclass Solution:\n def reorderList(self, head):\n arr, Iter = [], head\n while Iter:\n arr.append(Iter)\n Iter = Iter.next\n \n L, R = 1, len(arr)-1\n for i in range(len(arr)):\n if i & 1:\n head.next = arr[L]\n L += 1\n else:\n head.next = arr[R]\n R -= 1\n head = head.next\n head.next = None\n```\n\n***Time Complexity :*** <code>O(N)</code>, where `N` is the number of nodes in the linked list. We traverse linked list once and store it in array. Then we traverse the array once. Thus overall time- `O(2N) = O(N)`\n***Space Complexity :*** `O(N)`, required to store nodes of list into array\n\n---\n\n\u2714\uFE0F ***Solution - II (In-place Transformation)***\n\nIn the above solution, we are simply using two pointers, one to the start and one to the end of array. The nodes pointed by these pointers are picked in alternating manner and then these pointers are iterated in opposite directions. This **continues till they meet in the middle**, i.e, all nodes are covered in the process.\n\nBut we are using extra space in the form of array. We required array to be able to iterate the `R` pointer in the backward direction which wouldnt be possible if we directly used linked list. \n\nHowever, we can optimize the space by modifying our list to make it possible to iterate backwards from `R` pointer. We can simply reverse the 2nd half of the list which allows us to place `R` at the end and iterate backwards till the mid. Then the rest process remains similar in logic as above.\n\n* First **find the mid of linked list**. This can be done using slow & fast pointer algorithm\n* Then we **reverse the 2nd half** and place the `R` pointer at the end\n* Initialize `L` pointer to `head->next`\n* We can now simply **re-order by placing nodes from `L` and `R` pointers in alternating fashion** till they meet. \n\n\n\n**C++**\n```cpp\nclass Solution {\npublic:\n\t// 876. Middle of the Linked List - returns the mid of list using slow-fast pointer approach\n ListNode* middleNode(ListNode* head) {\n auto slow = head, fast = head;\n while(fast && fast -> next)\n slow = slow -> next,\n fast = fast -> next -> next; // fast moves at 2x speed\n return slow; // slow ends up at mid\n }\n\t// 206. Reverse Linked List - reverses and returns the head of reversed list\n ListNode* reverseList(ListNode* head) {\n ListNode *prev = nullptr;\n while(head) {\n auto nextNode = head -> next; // store next node before reversing next ptr of cur\n head -> next = prev; // reverse the next ptr to previous node\n prev = head; // update previous node as cur\n head = nextNode; // move to orignal next node\n }\n return prev; // returns head of reversed list\n }\n void reorderList(ListNode* head) {\n if(!head || !head -> next) return;\n auto mid = middleNode(head);\n auto R = reverseList(mid), L = head -> next;\n for(int i = 0; L != R; i++, head = head -> next) // re-order in alternating fashion \n if(i & 1) { \n head -> next = L;\n L = L -> next;\n }\n else {\n head -> next = R;\n R = R -> next;\n }\n }\n};\n```\n\n**Python**\n```python\nclass Solution:\n def reorderList(self, head):\n def middleNode(head):\n slow, fast = head, head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow\n \n def reverseList(head):\n prev = None\n while head:\n nextNode = head.next\n head.next = prev\n prev, head = head, nextNode\n return prev\n\n if not head or not head.next: return\n R, L, i = reverseList(middleNode(head)), head.next, 0\n while L != R:\n if i & 1:\n head.next, L = L, L.next\n else:\n head.next, R = R, R.next\n head, i = head.next, i + 1\n```\n\n***Time Complexity :*** <code>O(N)</code>, we need `O(N)` to find mid of list, another `O(N/2) = O(N)` to reverse the 2nd half and finally `O(N)` to re-order the list. Thus overall time: `O(3N) = O(N)`\n***Space Complexity :*** `O(1)`, only constant extra space is used\n\n---\n---\n\n\uD83D\uDCBBIf there are any suggestions / questions / mistakes in my post, comment below \uD83D\uDC47 \n\n---\n---\n\n
| 123 | 2 |
[]
| 11 |
reorder-list
|
Two Approaches✅|| Using Stack & Tortoise and Hare method 🔥|| Easy to understand
|
two-approaches-using-stack-tortoise-and-9a7v9
|
\n Describe your first thoughts on how to solve this problem. \n\n# Approach 1: ( Using Stack)\n1. It starts by traversing the linked list and pushing each node
|
mdsahil37621
|
NORMAL
|
2024-03-23T00:39:49.128675+00:00
|
2024-03-23T10:05:53.167587+00:00
| 20,162 | false |
\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach 1: ( Using Stack)\n1. It starts by traversing the linked list and pushing each node onto a stack. This effectively reverses the order of nodes.\n2. Then it starts traversing the list again from the beginning.\n3. During this traversal, it pops a node from the stack, connects it to the current node in the traversal, and moves forward.\n4. It continues this process until it encounters a situation where the current node and the node at the top of the stack are the same, which indicates the mid-point of the list.\n5. At this point, it breaks the connection to the next node (to avoid cycles) and stops the process.\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```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n stack<ListNode*> s;\n ListNode* curr = head;\n while(curr){\n s.push(curr);\n curr = curr->next;\n }\n curr = head;\n unordered_map<ListNode*, bool> vis;\n while(true){\n ListNode* last = s.top();\n s.pop();\n ListNode* next = curr->next;\n vis[curr] = true;\n if(vis[last]){ \n curr->next = NULL; \n break; \n } \n curr->next = last; \n vis[last] = true;\n curr = curr->next; \n if(vis[next]){\n curr->next = NULL;\n break;\n }\n curr->next = next;\n curr = curr->next;\n }\n }\n};\n```\n# Approach 2: (Tortoise and Hare method)\nTwo pointer Approach Algorithm:\n\n1. First let\'s take two pointers name it as half and temp . temp is faster than half by 1.\n2. When temp reaches the end of linkedlsit half reaches the middle element .So this is how the linkedlist will get divided in two halfes as the center will become a dividing node .\n3. Now reverse the second half .\n4. After reversing the second half, merge the first half and second half.\n\n```\n//Upvote and Comment\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n // base case : linkedlist is empty\n if (!head) return;\n \n // finding the middle with the help of two pointer approach\n ListNode *tmp = head, *half = head, *prev = NULL;\n while (tmp->next && tmp->next->next) {\n tmp = tmp->next->next;\n half = half->next;\n }\n \n // adding one bit in case of lists with even length\n if (tmp->next) half = half->next;\n \n // Now reverse the second half\n while (half) {\n tmp = half->next;\n half->next = prev;\n prev = half;\n half = tmp;\n }\n half = prev;\n \n // After reversing the second half, let\'s merge both the halfes\n while (head && half) {\n tmp = head->next;\n prev = half->next;\n head->next = half;\n half->next = tmp;\n head = tmp;\n half = prev;\n }\n \n // Base case : closing when we had even length arrays\n if (head && head->next) head->next->next = NULL;\n }\n};\n```\n\n\n
| 122 | 0 |
['Two Pointers', 'Stack', 'C++']
| 14 |
reorder-list
|
3 steps to solve the question
|
3-steps-to-solve-the-question-by-niits-5ty8
|
Reordering a linked list can be a challenging problem, but with the right approach, it becomes manageable. In this article, we’ll explain the theory behind solv
|
niits
|
NORMAL
|
2024-12-16T18:24:06.314582+00:00
|
2024-12-16T18:27:45.176458+00:00
| 11,710 | false |
Reordering a linked list can be a challenging problem, but with the right approach, it becomes manageable. In this article, we\u2019ll explain the theory behind solving this problem and provide a step-by-step explanation of the solution. We\u2019ll also visualize the key steps for better understanding.\n\n# Solution Video\n\nhttps://youtu.be/I4DPcLkgUmA\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 11,972\nThank you for your support!\n\n---\n\n## Problem Statement\n\nGiven the head of a singly linked list, reorder the list in the following manner:\n\n- The first element is followed by the last element.\n- The second element is followed by the second-to-last element.\n- And so on.\n\nFor example:\n\n- Input: `1 \u2192 2 \u2192 3 \u2192 4 \u2192 5`\n- Output: `1 \u2192 5 \u2192 2 \u2192 4 \u2192 3`\n\n### Constraints\n\n1. You must solve the problem in-place (i.e., without using extra memory for another list).\n2. The algorithm should run efficiently.\n\n---\n\n## Approach and Theory\n\nThe solution can be broken down into three key steps:\n\n### Step 1: Splitting the List into Two Halves\n\nUsing the **two-pointer technique**, we can identify the middle of the list:\n\n- `slow` moves one step at a time.\n- `fast` moves two steps at a time.\n\nWhen `fast` reaches the end, `slow` will be at the midpoint of the list.\n\nExample:\n\n- Input: `1 \u2192 2 \u2192 3 \u2192 4 \u2192 5`\n- After splitting: `1 \u2192 2 \u2192 3` and `4 \u2192 5`\n\n### Step 2: Reversing the Second Half\n\nNext, we reverse the second half of the list. Starting from the node after `slow`, we use a standard iterative reversal process to reverse the pointers.\n\nExample:\n\n- Before reversing: `4 \u2192 5`\n- After reversing: `5 \u2192 4`\n\n### Step 3: Merging the Two Halves\n\nFinally, we merge the two halves alternately:\n\n- Take a node from the first half, then a node from the reversed second half.\n- Repeat until all nodes are merged.\n\nExample:\n\n- First half: `1 \u2192 2 \u2192 3`\n- Reversed second half: `5 \u2192 4`\n- Merged: `1 \u2192 5 \u2192 2 \u2192 4 \u2192 3`\n\n---\n\n## Visual Explanation\n\n### Initial List\n```\n1 \u2192 2 \u2192 3 \u2192 4 \u2192 5\n```\n\n### Step 1: Splitting the List\n\n1. Initialize `slow` and `fast` to the head of the list.\n2. Move `slow` one step and `fast` two steps at a time.\n\n```\nslow: 3\nfast: null (end of the list)\n```\n\nList is split:\n```\nFirst half: 1 \u2192 2 \u2192 3\nSecond half: 4 \u2192 5\n```\n\n---\n\n### Step 2: Reversing the Second Half\n\nUsing an iterative reversal process:\n\n- Start with `node = null` and `second = 4 \u2192 5`.\n\n1. Reverse 4:\n```\nnode: 4 \u2192 null\nsecond: 5\n```\n\n2. Reverse 5:\n```\nnode: 5 \u2192 4 \u2192 null\nsecond: null\n```\n\nReversed second half:\n```\n5 \u2192 4\n```\n\n---\n\n### Step 3: Merging the Two Halves\n\n1. Initialize:\n - `first = 1 \u2192 2 \u2192 3`\n - `second = 5 \u2192 4`\n\n2. Merge nodes alternately:\n\n - Take `1` from `first` and `5` from `second`:\n ```\n 1 \u2192 5\n ```\n\n - Take `2` from `first` and `4` from `second`:\n ```\n 1 \u2192 5 \u2192 2 \u2192 4\n ```\n\n - Take `3` from `first` (second is now null):\n ```\n 1 \u2192 5 \u2192 2 \u2192 4 \u2192 3\n ```\n\n---\n\nhttps://youtu.be/pCc4kR-TdYs\n\n---\n\n\n## Complete Code\n\n```python []\nclass Solution:\n def reorderList(self, head: Optional[ListNode]) -> None:\n fast = head\n slow = head\n\n # Step 1: Find the middle of the list\n while fast and fast.next:\n fast = fast.next.next\n slow = slow.next\n\n # Step 2: Reverse the second half of the list\n second = slow.next\n slow.next = None\n node = None\n\n while second:\n temp = second.next\n second.next = node\n node = second\n second = temp\n\n # Step 3: Merge the two halves\n first = head\n second = node\n\n while second:\n temp1, temp2 = first.next, second.next\n first.next, second.next = second, temp1\n first, second = temp1, temp2\n```\n```javascript []\nvar reorderList = function(head) {\n if (!head) return;\n\n // Step 1: Find the middle of the list\n let slow = head, fast = head;\n while (fast && fast.next) {\n slow = slow.next;\n fast = fast.next.next;\n }\n\n // Step 2: Reverse the second half of the list\n let second = slow.next;\n slow.next = null;\n let node = null;\n\n while (second) {\n const temp = second.next;\n second.next = node;\n node = second;\n second = temp;\n }\n\n // Step 3: Merge the two halves\n let first = head;\n second = node;\n\n while (second) {\n const temp1 = first.next, temp2 = second.next;\n first.next = second;\n second.next = temp1;\n first = temp1;\n second = temp2;\n } \n};\n```\n```java []\nclass Solution {\n public void reorderList(ListNode head) {\n if (head == null) return;\n\n // Step 1: Find the middle of the list\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n\n // Step 2: Reverse the second half of the list\n ListNode second = slow.next;\n slow.next = null;\n ListNode node = null;\n\n while (second != null) {\n ListNode temp = second.next;\n second.next = node;\n node = second;\n second = temp;\n }\n\n // Step 3: Merge the two halves\n ListNode first = head;\n second = node;\n\n while (second != null) {\n ListNode temp1 = first.next, temp2 = second.next;\n first.next = second;\n second.next = temp1;\n first = temp1;\n second = temp2;\n } \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n if (!head) return;\n\n // Step 1: Find the middle of the list\n ListNode* slow = head;\n ListNode* fast = head;\n while (fast && fast->next) {\n slow = slow->next;\n fast = fast->next->next;\n }\n\n // Step 2: Reverse the second half of the list\n ListNode* second = slow->next;\n slow->next = nullptr;\n ListNode* node = nullptr;\n\n while (second) {\n ListNode* temp = second->next;\n second->next = node;\n node = second;\n second = temp;\n }\n\n // Step 3: Merge the two halves\n ListNode* first = head;\n second = node;\n\n while (second) {\n ListNode* temp1 = first->next;\n ListNode* temp2 = second->next;\n first->next = second;\n second->next = temp1;\n first = temp1;\n second = temp2;\n }\n }\n};\n```\n\n---\n\n## Complexity Analysis\n\n1. **Time Complexity**: $$O(n)$$\n - Finding the middle takes $$O(n)$$.\n - Reversing the second half takes $$O(n/2)$$.\n - Merging the two halves takes $$O(n)$$.\n\n2. **Space Complexity**: $$O(1)$$\n - The algorithm uses constant extra space as it modifies the list in-place.\n\n---\n\n## Conclusion\n\nBy splitting the list, reversing the second half, and merging the halves, we can reorder the list efficiently in $$O(n)$$ time and $$O(1)$$ space. This approach demonstrates the power of combining basic techniques like the two-pointer method and iterative reversal to solve seemingly complex problems.\n\n---\n\nThank you for reading my post.\n\n##### \u2B50\uFE0F Subscribe URL\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n##### \u2B50\uFE0F Related Video\n#206 Reverse Linked List\n\nhttps://youtu.be/9TsQmdRAxT8\n\n
| 118 | 0 |
['Linked List', 'Two Pointers', 'C++', 'Java', 'Python3']
| 1 |
reorder-list
|
Easily Expalined Step by Step Code. (100% Beats and 0ms Runtime)
|
easily-expalined-step-by-step-code-100-b-ay0o
|
Intuition\nFind the middle of the linked list. For Example:-\n 1->2->3->4->5\nHere, middle =3;\nThen reverse the second half of the Linked List (i.e. 4->5),
|
KumarNishantGunjan
|
NORMAL
|
2023-02-06T02:06:57.353909+00:00
|
2024-03-23T04:09:44.935932+00:00
| 11,209 | false |
# Intuition\nFind the middle of the linked list. For Example:-\n 1->2->3->4->5\nHere, middle =3;\nThen reverse the second half of the Linked List (i.e. 4->5), so after reversing the list will be like 5->4\nNow, merege both list in ordered way like one element of 1st half linkedlist (i.e 1->2->3) and one element of second half list (i.e 5->4) so after merging the list will be like:-\n 1->5->2->4->3\nwhich is the required answer.\n\n# Approach\nFor finding the middle of the linked list we can use slow and fast pointer approach.\nFor reversing the list we can use the [Reverse linkedList I ](https://leetcode.com/problems/reverse-linked-list/solutions/3111776/100-beats-and-0ms-runtime-easy-java-solution/?orderBy=most_votes) approach.\nThen we can merge list one by one.\n\n# Complexity\n- Time complexity: $$O(n)$$\n \n\n- Space complexity: $$O(1)$$\n \n \n```Java []\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public void reorderList(ListNode head) {\n // if head will be null or head.next will be null simply return ;\n if(head==null || head.next==null)return ;\n\n //finding middle element\n ListNode slow = head;\n ListNode fast= head;\n while(fast!=null && fast.next!=null){\n slow=slow.next;\n fast=fast.next.next;\n }\n \n// reversing the second half of the list\n ListNode newNode = reverseList(slow.next);\n // breaking the list from the middle\n slow.next=null;\n //merging both list\n //first half list pointer\n ListNode curr = head;\n //second half list pointer\n ListNode dummy = newNode;\n while(curr!=null && dummy!=null){\n //pointer to store next element of curr(1st half list)\n ListNode temp = curr.next;\n //link element of 1st half to that of second half\n curr.next=dummy;\n //pointer to store next element of dummy(2nd half list)\n ListNode temp2=dummy.next;\n //link the rest of the first half list\n dummy.next=temp;\n //increment curr and dummy pointer to do the same thing again and again util we reach end of the any one list or both list\n curr=temp;\n dummy=temp2;\n }\n\n }\n\n // method to reverse the linkedList\n public ListNode reverseList(ListNode node){\n ListNode prev = null;\n ListNode curr = node;\n ListNode next = null;\n while(curr!=null){\n next=curr.next;\n curr.next=prev;\n prev=curr;\n curr=next;\n }\n \n return prev;\n }\n}\n```\n```C++ []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\n#include <iostream>\n\nusing namespace std;\n\n// Definition for singly-linked list\n \n\nclass Solution {\npublic:\n // Function to reorder a linked list\n void reorderList(ListNode* head) {\n // If head is null or there\'s only one node, no reordering needed\n if (!head || !head->next)\n return;\n\n // Find the middle of the list\n ListNode* slow = head;\n ListNode* fast = head;\n while (fast && fast->next) {\n slow = slow->next;\n fast = fast->next->next;\n }\n\n // Reverse the second half of the list\n ListNode* newNode = reverseList(slow->next);\n slow->next = nullptr;\n\n // Merge both halves of the list\n ListNode* curr = head;\n ListNode* dummy = newNode;\n while (curr && dummy) {\n ListNode* temp = curr->next;\n curr->next = dummy;\n ListNode* temp2 = dummy->next;\n dummy->next = temp;\n curr = temp;\n dummy = temp2;\n }\n }\n\n // Function to reverse a linked list\n ListNode* reverseList(ListNode* node) {\n ListNode* prev = nullptr;\n ListNode* curr = node;\n ListNode* next = nullptr;\n while (curr) {\n next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n\n return prev;\n }\n};\n\n \n\n```\n \n\n\n[Nishant Kumar](https://leetcode.com/KumarNishantGunjan/)\n\n\n
| 111 | 0 |
['Linked List', 'C++', 'Java']
| 4 |
reorder-list
|
Java | 2 Approach | 2 Pointer Approach
|
java-2-approach-2-pointer-approach-by-ab-j6aj
|
Solution 1 - Split linked list\n\n---\nsuppose we have two linkedList :\n>l1 = 1 -> 2 -> 3\n>l2 = 4 -> 5 -> 6 ,\n> l2rev = 6 -> 5 -> 4\n\n Now if we have to
|
abhi9720
|
NORMAL
|
2021-12-22T06:11:47.155829+00:00
|
2021-12-24T04:45:11.174022+00:00
| 10,621 | false |
***Solution 1* - Split linked list**\n\n---\nsuppose we have two linkedList :\n>`l1 = 1 -> 2 -> 3`\n>` l2 = 4 -> 5 -> 6` ,\n> **l2rev** = ` 6 -> 5 -> 4 `\n\n* Now if we have to merge **l1** and **l2rev** then this question is going to bit more simpler right\n\t**Now how do we merge :**\n\t\t**p1 = l1**\n\t\t**p2 = l2rev**\n\t* p1 is always point to node whose next is going to fill \n\t* p2 point to to node which is going to fill in **p1 next**\n\n**So steps involve are :**\n* split linkedlist into two halves\n\t* find mid and split\n\t* and revese second half\n* merge these two halves\n\n### Lets Code this Approch \uD83D\uDC69\uD83C\uDFFB\u200D\uD83D\uDCBB \uD83D\uDCBB\n---\n```\nclass Solution {\n public ListNode midNode(ListNode head){\n ListNode fast = head, slow = head;\n while(fast.next!=null && fast.next.next!=null){\n fast = fast.next.next;\n slow = slow.next;\n }\n return slow;\n }\n \n public ListNode reverse(ListNode head){\n ListNode curr = head, prev= null, next = null;\n while(curr!=null){\n next = curr.next;\n curr.next = prev ;\n prev = curr;\n curr = next;\n }\n return prev;\n }\n\n \n public void reorderList(ListNode head) {\n \n ListNode midNode = midNode(head);\n ListNode nextToMid = midNode.next;\n midNode.next = null;\n ListNode p2 = reverse(nextToMid);\n \n ListNode p1 = head ,p1Next; \n while(p1!=null && p2!=null){\n p1Next = p1.next; \n\t\t\tp1.next = p2;\n\t\t\t \n p1 = p2;\n p2=p1Next; \n } \n } \n}\n```\n\n\n---\n\nTIME COMPLEXITY : **O(n)**\nSPACE COMPLEXITY : **O(1)**\n\n\n---\n\n\n***Solution 2* - Single traversal (Important concept)**\n\n---\n\n> Now let suppose we have two pointer left and right if we can move left **forward** and right **backward** then our task is going to simpler right \n\n**To merge we need to write only this much code**\n```\nLeftnext = left.next;\nleft.next = right;\nrigt.next = Leftnext\nleft = Leftnext\n```\n\n## let get more insight \uD83D\uDCA1\n---\n> \n\n***Now How do we move two pointer one forward and one backward in linked list***\n- When we make recursion call on linkedlist then in post area of recursion call our stack pointer is moving in backward direction:\n- And to move pointer in forward dirn at the same time , make it in heap , we have two ways to make it in heap\n\t 1. use class variable (declare outside the function)\n\t 2. Make one size array (it also created in heap), we are using this \n\n### Lets Code to get approch more better \uD83D\uDC69\uD83C\uDFFB\u200D\uD83D\uDCBB\uD83D\uDCBB :\n---\n```\n\nclass Solution {\n public void reorderList(ListNode head) {\n ListNode [] left = new ListNode[1];// it will create in heap\n left[0] = head;\n reorder(left,head);\n \n }\n \n // left pointer will be created in heap and right pointer will be created in stack\n public void reorder(ListNode left[],ListNode right){\n if(right==null){\n return ;\n }\n reorder(left,right.next);\n \n // in post area of recursion right pointer coming back(because of function remove from recursion stack)\n // and we move left pointer forward \n if(left[0].next!=null){\n ListNode leftNext = left[0].next;\n left[0].next = right;\n right.next = leftNext;\n left[0] = leftNext; \n }\n \n // as we need to merge till left pointer behind the right pointer \n if(left[0].next == right){\n left[0].next = null;\n } \n }\n}\n```\n\n---\nTIME COMPLEXITY : **O(n)**\nSPACE COMPLEXITY : **O(n), if we consider recursion stack**\n\n\n---\n\n
| 100 | 12 |
['Two Pointers', 'Java']
| 10 |
reorder-list
|
Share a consise recursive solution in C++
|
share-a-consise-recursive-solution-in-c-w6io6
|
\n The recursive idea have been posted by yucheng.wang. Given a example, 1->2->3->4->5, the solution will reorder node(3), then reorder 2 and 4 to have (2->4->
|
windflower_ict
|
NORMAL
|
2015-03-27T22:33:12+00:00
|
2018-10-10T17:35:35.449175+00:00
| 12,708 | false |
\n The recursive idea have been posted by yucheng.wang. Given a example, 1->2->3->4->5, the solution will reorder node(3), then reorder 2 and 4 to have (2->4->3), then 1 and 5 get have 1->5->2->4->3. Each call of reorderList(ListNode* head, int len) will return the last element after this reorderList() call.\n\n int getLength(ListNode *head){\n int len = 0;\n while( head != NULL ){\n ++len; head = head->next;\n }\n return len;\n }\n \n ListNode * reorderList(ListNode *head, int len){\n if(len == 0)\n return NULL;\n if( len == 1 )\n return head;\n if( len == 2 )\n return head->next;\n ListNode * tail = reorderList(head->next, len-2);\n ListNode * tmp = tail->next;\n tail->next = tail->next->next;\n tmp->next = head->next;\n head->next = tmp;\n return tail;\n }\n \n void reorderList(ListNode *head) { //recursive\n ListNode * tail = NULL;\n tail = reorderList(head, getLength(head));\n }
| 72 | 2 |
[]
| 10 |
reorder-list
|
✅ [Python/Java/C++] 2 Easy Solutions || Visualized Explanation || Beginner Friendly
|
pythonjavac-2-easy-solutions-visualized-a8kn3
|
Please UPVOTE if you LIKE! \uD83D\uDE01\n step 1: find the middle pointer of the linked list and split the linked list into two halves using slow and fast point
|
linfq
|
NORMAL
|
2021-12-22T03:51:43.177223+00:00
|
2021-12-31T17:03:34.305178+00:00
| 4,315 | false |
**Please UPVOTE if you LIKE!** \uD83D\uDE01\n* **step 1: find the middle pointer of the linked list and split the linked list into two halves using slow and fast pointers**\n\t```\n\t\t\t\t\t\t\t\t\thead = [1, 2, 3]\n\thead = [1, 2, 3, 4, 5] =>\n\t\t\t\t\t\t\t\t\tmid = [4, 5]\n\t```\n* **step 2: reverse the second half**\n\t```\n\thead = [1, 2, 3]\n\tmid = [4, 5] => mid = [5, 4]\n\t```\n* **step 3: interleaving merge the first half and the reversed second half**\n\t```\n\thead = [1, 2, 3]\n\t\t\t\t\t\t => head = [1, 5, 2, 4, 3]\n\tmid = [5, 4]\n\t```\n\n\n```\nTime Complexity: O(N)\nSpace Complexity: O(1)\n```\n\n<iframe src="https://leetcode.com/playground/b7s3MeYC/shared" frameBorder="0" width="100%" height="650"></iframe>\n\n**Basic Solution Using Array or Deque and Repeat `pop_left()` and` pop()`**\n```\n# algorithm pseudo code\ndq = [1, 2, 3, 4, 5]\nwhile dq:\n\tdq.pop_left()\n\tif dq: dq.pop()\n```\n\n```\ndq = [1, 2, 3, 4, 5] => dq.pop_left() => 1\ndq = [2, 3, 4, 5] => dq.pop() => 5\ndq = [2, 3, 4] => dq.pop_left() => 2\ndq = [3, 4] => dq.pop() => 4\ndq = [3] => dq.pop_left() => 3\n```\n\n```\nTime Complexity: O(N)\nSpace Complexity: O(N)\n```\n<iframe src="https://leetcode.com/playground/iTNS2J3s/shared" frameBorder="0" width="100%" height="450"></iframe>\n\n**If you have any question, feel free to ask. If you like the solution or the explanation, Please UPVOTE!**
| 64 | 6 |
[]
| 8 |
reorder-list
|
[Python] 2 solutions: Stack, 3 steps - Clean & Concise
|
python-2-solutions-stack-3-steps-clean-c-dma7
|
\u2714\uFE0F Solution 1: Using Stack\n- The idea is that we use stack to store all nodes in the linked list. Then the top of the stack is the last node.\n- Iter
|
hiepit
|
NORMAL
|
2020-04-07T16:03:56.534002+00:00
|
2021-09-27T08:45:02.573380+00:00
| 1,787 | false |
**\u2714\uFE0F Solution 1: Using Stack**\n- The idea is that we use stack to store all nodes in the linked list. Then the top of the stack is the last node.\n- Iterate `len(st) // 2` times, link in order:\n\t- `nxt = head.next`\n\t- `head -> st.pop() -> nxt`\n\t- `head = nxt`.\n\n\n```python\nclass Solution:\n def reorderList(self, head: Optional[ListNode]) -> None:\n """\n Do not return anything, modify head in-place instead.\n """\n st = []\n cur = head\n while cur != None:\n st.append(cur)\n cur = cur.next\n \n for i in range(len(st) // 2):\n nxt = head.next\n head.next = st.pop()\n head = head.next\n head.next = nxt\n head = head.next\n \n if head != None:\n head.next = None\n```\nComplexity:\n- Time: `O(N)`, where `N <= 5 * 10^4` is number of nodes in the linked list.\n- Space: `O(N)`\n\n---\n**\u2714\uFE0F Solution 2: 3 steps**\n- Step 1: Find the middle of the linked list then cut the middle into 2 halfs.\n- Step 2: Reverse the last half of the linked list.\n- Step 3: Merge 2 list one by one.\n```python\nclass Solution:\n def reorderList(self, head: Optional[ListNode]) -> None:\n """\n Do not return anything, modify head in-place instead.\n """\n def findMiddle(head): # return mid, prevMid\n prevSlow = None\n slow = fast = head\n while fast != None and fast.next != None:\n prevSlow = slow\n slow = slow.next\n fast = fast.next.next\n return slow, prevSlow\n \n def reverse(head):\n newHead = None\n while head != None:\n nxt = head.next\n head.next = newHead\n newHead = head\n head = nxt\n return newHead\n \n def mergeOneByOne(head1, head2):\n dummyNode = curHead = ListNode(0)\n while head1 != None and head2 != None:\n curHead.next = head1\n curHead = curHead.next\n head1 = head1.next\n \n curHead.next = head2\n curHead = curHead.next\n head2 = head2.next\n \n if head1 != None:\n curHead.next = head1\n elif head2 != None:\n curHead.next = head2\n \n return dummyNode.next\n \n \n # Step 1: Find the middle of the linked list and cut the middle into 2 halfs\n mid, prevMid = findMiddle(head)\n if prevMid == None: return head # Case one element\n prevMid.next = None # cut the middle into 2 halfs\n \n # Step 2: Reverse the last half of the linked list\n half = reverse(mid)\n \n # Step 3: Merge 2 list one by one\n return mergeOneByOne(head, half)\n```\nComplexity:\n- Time: `O(N)`, where `N <= 5 * 10^4` is number of nodes in the linked list.\n- Space: `O(1)`
| 63 | 1 |
[]
| 2 |
reorder-list
|
Python solution
|
python-solution-by-zitaowang-roda
|
The algorithm consists of two steps: 1. reverse the second half of the list; 2. Insert the second half of the list into the first half appropriately. \n\nTo ach
|
zitaowang
|
NORMAL
|
2018-12-24T23:17:42.682498+00:00
|
2018-12-24T23:17:42.682542+00:00
| 5,218 | false |
The algorithm consists of two steps: 1. reverse the second half of the list; 2. Insert the second half of the list into the first half appropriately. \n\nTo achieve the first step, we initialize a slow pointer `slow` and a fast pointer `fast`, with the `fast` travels twice as fast as the `slow`, so that when `fast` reaches the end of the list, `slow` reaches the middle of the list. Then we can reverse the links between every node to the right of `slow`. \n\nTo achieve the second step, we initialze another pointer `trav = head`. Then we can make `trav` and `fast` both travel to the middle of the list, and in each step, insert `fast` between `trav` and `trav.next`.\n\nWe illustrate with two examples. Consider first the following list with even length:\n```\n1 -> 2 -> 3 -> 4 (before step 1)\n1 -> 2 -> 3 <- 4 (after step 1, before step 2)\n1 -> 4 -> 2 -> 3 (after step 2)\n```\nNext, consider the following list with odd length:\n```\n1 -> 2 -> 3 -> 4 -> 5 (before step 1)\n1 -> 2 -> 3 <- 4 <- 5 (after step 1, before step 2)\n1 -> 4 -> 2 -> 5 -> 3 (after step 2)\n```\n\nTime complexity: `O(n)`, space complexity: `O(1)`.\n\n```\nclass Solution:\n def reorderList(self, head):\n """\n :type head: ListNode\n :rtype: void Do not return anything, modify head in-place instead.\n """\n if not head or not head.next:\n return\n slow = head\n fast = head.next\n while fast.next and fast.next.next:\n slow = slow.next\n fast = fast.next.next\n slow = slow.next\n if fast.next:\n fast = fast.next\n \n # reverse the second half of the list\n prev = slow\n curr = slow.next\n prev.next = None\n while curr:\n tmp = curr.next\n curr.next = prev\n prev = curr\n curr = tmp\n \n # turn the list into zigzag manner\n trav = head\n while fast.next:\n tmp1 = trav.next\n tmp2 = fast.next\n trav.next = fast\n fast.next = tmp1\n trav = tmp1\n fast = tmp2\n```
| 55 | 0 |
[]
| 7 |
reorder-list
|
Reverse Second Half And Merge the Lists | | Two-Pointer | | C++ | | Java | | Python3 | | ✅✅✅🔥🔥🔥
|
reverse-second-half-and-merge-the-lists-ey7p5
|
\n\n Here\'s a response that directly uses the variables from the provided code:\n\nIntuition:\n\n- We\'ll rearrange the linked list using three key steps: find
|
Hunter_0718
|
NORMAL
|
2024-03-23T01:47:22.106955+00:00
|
2024-03-23T01:59:19.333076+00:00
| 15,716 | false |
\n\n **Here\'s a response that directly uses the variables from the provided code:**\n\n**Intuition:**\n\n- We\'ll rearrange the linked list using three key steps: finding the middle node, reversing the second half, and merging the two halves in an alternating pattern.\n\n**Approach:**\n\n1. **Find the Middle Node:**\n - Initialize `slow` and `fast` pointers to `head`.\n - While `fast` and `fast->next` exist, move `slow` one step and `fast` two steps.\n - `slow` will now point to the middle node.\n\n2. **Reverse the Second Half:**\n - Call `reverse(slow)` to reverse the list starting from `slow`.\n - This returns the new head of the reversed portion (`list2`).\n\n3. **Merge the Two Halves:**\n - Keep a `prev` pointer to set `prev->next` to `NULL` later, marking the end of the first half.\n - Iterate through `list1` and `list2`:\n - Store `list1->next` as `nextNode`.\n - Connect `list1->next` to `list2`.\n - Move `list1` to `nextNode`.\n - Move `list2` to `list2->next`.\n\n**Time Complexity:**\n\n- Finding middle: O(n)\n- Reversing: O(n/2) ~ O(n)\n- Merging: O(n)\n- Total: O(3n) ~ O(n)\n\n**Space Complexity:**\n\n- Extra pointers: O(1)\n- Recursive `reverse` call stack: O(n) in worst-case (extremely long lists), but practically considered O(1).\n\n```C++ []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* reverse(ListNode *head){\n if(!head) return NULL;\n ListNode *prev = NULL;\n ListNode *curr = head;\n ListNode *nextNode = NULL;\n while(curr){\n nextNode = curr->next;\n curr->next = prev;\n prev = curr;\n curr = nextNode;\n }\n return prev;\n }\n\n void merge(ListNode *list1, ListNode *list2){\n while(list2) {\n ListNode *nextNode = list1->next;\n list1->next = list2;\n list1 = list2;\n list2 = nextNode;\n\n }\n\n }\n void reorderList(ListNode* head) {\n if(!head || !head->next) return;\n ListNode *slow = head;\n ListNode *fast = head;\n ListNode *prev = head;\n while(fast && fast->next){\n prev = slow;\n fast = fast->next->next;\n slow = slow->next;\n }\n prev->next = NULL;\n ListNode *list1 = head;\n ListNode *list2 = reverse(slow);\n merge(list1,list2);\n }\n};\n```\n```Java []\n/*class ListNode {\n int val;\n ListNode next;\n ListNode() {}\n ListNode(int val) { this.val = val; }\n ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n}*/\n\nclass Solution {\n public ListNode reverse(ListNode head) {\n if (head == null) return null;\n ListNode prev = null;\n ListNode curr = head;\n ListNode nextNode = null;\n while (curr != null) {\n nextNode = curr.next;\n curr.next = prev;\n prev = curr;\n curr = nextNode;\n }\n return prev;\n }\n\n public void merge(ListNode list1, ListNode list2) {\n while (list2 != null) {\n ListNode nextNode = list1.next;\n list1.next = list2;\n list1 = list2;\n list2 = nextNode;\n }\n }\n\n public void reorderList(ListNode head) {\n if (head == null || head.next == null) return;\n ListNode slow = head;\n ListNode fast = head;\n ListNode prev = head;\n while (fast != null && fast.next != null) {\n prev = slow;\n fast = fast.next.next;\n slow = slow.next;\n }\n prev.next = null;\n ListNode list1 = head;\n ListNode list2 = reverse(slow);\n merge(list1, list2);\n }\n}\n\n```\n```Python3 []\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\nclass Solution:\n def reverse(self, head):\n if not head:\n return None\n prev = None\n curr = head\n nextNode = None\n while curr:\n nextNode = curr.next\n curr.next = prev\n prev = curr\n curr = nextNode\n return prev\n\n def merge(self, list1, list2):\n while list2:\n nextNode = list1.next\n list1.next = list2\n list1 = list2\n list2 = nextNode\n\n def reorderList(self, head):\n if not head or not head.next:\n return\n slow = head\n fast = head\n prev = head\n while fast and fast.next:\n prev = slow\n fast = fast.next.next\n slow = slow.next\n prev.next = None\n list1 = head\n list2 = self.reverse(slow)\n self.merge(list1, list2)\n\n```\n\n```JavaScript []\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val === undefined ? 0 : val)\n * this.next = (next === undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {void} Do not return anything, modify head in-place instead.\n */\nvar reorderList = function(head) {\n if (!head || !head.next) return;\n \n // Find the middle of the linked list\n let slow = head;\n let fast = head;\n while (fast.next && fast.next.next) {\n slow = slow.next;\n fast = fast.next.next;\n }\n \n // Reverse the second half of the linked list\n let prev = null;\n let curr = slow.next;\n while (curr) {\n let nextNode = curr.next;\n curr.next = prev;\n prev = curr;\n curr = nextNode;\n }\n slow.next = null;\n \n // Merge the two halves\n let p1 = head;\n let p2 = prev;\n while (p1 && p2) {\n let nextP1 = p1.next;\n let nextP2 = p2.next;\n p1.next = p2;\n p2.next = nextP1;\n p1 = nextP1;\n p2 = nextP2;\n }\n};\n\n```\n\n\n\n**Dry Run:**\n\n**Example:** `head = [1, 2, 3, 4]`\n\n1. **Find Middle:**\n - `slow` = 1, `fast` = 4 (after loop)\n - Middle node: `slow = 2`\n\n2. **Reverse:**\n - `list2` = `reverse(2)` = `4 -> 3 -> 2`\n\n3. **Merge:**\n - `list1` = `1 -> 2 -> 3 -> 4`, `list2` = `4 -> 3 -> 2`\n - Iteration 1: `list1 = 1 -> 4`, `list2 = 3 -> 2`, `prev->next = NULL`\n - Iteration 2: `list1 = 4 -> 3`, `list2 = 2`\n - Final list: `1 -> 4 -> 2 -> 3`\n
| 47 | 2 |
['Linked List', 'Two Pointers', 'C++', 'Java', 'Python3', 'JavaScript']
| 10 |
reorder-list
|
Java solution with stack
|
java-solution-with-stack-by-wksora-bveq
|
I see no one use stack with java as the same idea as me, so I share my code here.\n\nIt is a bit straightforward, so need not explaination.\n\n public class
|
wksora
|
NORMAL
|
2014-12-18T01:54:42+00:00
|
2014-12-18T01:54:42+00:00
| 7,194 | false |
I see no one use stack with java as the same idea as me, so I share my code here.\n\nIt is a bit straightforward, so need not explaination.\n\n public class Solution {\n public void reorderList(ListNode head) {\n if (head==null||head.next==null) return;\n Deque<ListNode> stack = new ArrayDeque<ListNode>();\n ListNode ptr=head;\n while (ptr!=null) {\n stack.push(ptr); ptr=ptr.next;\n }\n int cnt=(stack.size()-1)/2;\n ptr=head;\n while (cnt-->0) {\n ListNode top = stack.pop();\n ListNode tmp = ptr.next;\n ptr.next=top;\n top.next=tmp;\n ptr=tmp;\n }\n stack.pop().next=null;\n }\n }
| 46 | 2 |
['Java']
| 9 |
reorder-list
|
[JAVA] One Pass Recursive Solution With Animation Explanation
|
java-one-pass-recursive-solution-with-an-7nu4
|
animation explaination\n\n\n\n\nclass Solution {\n \n private ListNode temp;\n private boolean isStop;\n\n public void reorderList(ListNode head) {\
|
ikws4
|
NORMAL
|
2021-02-10T11:10:05.750380+00:00
|
2021-02-18T00:18:39.822398+00:00
| 2,287 | false |
[animation explaination](https://docs.google.com/presentation/d/e/2PACX-1vQ-Oy-oQ0i4CvWbo8gf9-v42gVOb5gS76sJvhG7jqIntQV7R1dDG3tS7YUhRiPqYXBCjqCcVsJUeZjG/pub?start=true&loop=false&delayms=1500)\n\n<img src="https://assets.leetcode.com/users/images/0b44167d-f0c4-409a-bb80-9cab9e6b05e0_1612957822.2802742.png" width="600px" />\n\n```\nclass Solution {\n \n private ListNode temp;\n private boolean isStop;\n\n public void reorderList(ListNode head) {\n temp = head;\n isStop = false;\n reorder(head);\n }\n\n private void reorder(ListNode head) {\n if (head == null) return;\n reorder(head.next);\n\n if (!isStop) {\n ListNode next = temp.next;\n temp.next = head;\n head.next = next;\n temp = next;\n }\n\n if (temp != null && temp.next == head) {\n temp.next = null;\n isStop = true;\n }\n }\n}\n```
| 43 | 0 |
['Recursion', 'Java']
| 9 |
reorder-list
|
[C++] Simple Recursive vs. Iterative Approaches Compared and Explained, ~10% Time, ~60% Space
|
c-simple-recursive-vs-iterative-approach-i1zy
|
Core ideas:\n we have to run through the list to find the penultimate, not the last node;\n once we have it, we can also access the last and we set the the seco
|
ajna
|
NORMAL
|
2020-08-20T07:56:53.669853+00:00
|
2020-08-20T22:17:30.975215+00:00
| 5,633 | false |
Core ideas:\n* we have to run through the list to find the penultimate, not the last node;\n* once we have it, we can also access the last and we set the the second node to follow the last, last to follow the head and `NULL` the penultimate;\n* after that, we call `reorderList` on the third node;\n* if the list has less than 3 elements, no point in proceeding, so we `return` (our base case);\n\nTime performance is rather low (I go more or less quadratic here), but unless you change the values and/or use a bunch of extra memory to store the most of the list in some collection, I don\'t see many other ways around than iterating through it a bunch of times; I might try the other approach later, but that is clearly less fun.\n\nThe recursive code:\n\n```cpp\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n // base case handled here\n if (!head || !head->next || !head->next->next) return;\n // we need to find the penultimate node in order to proceed\n ListNode* penultimate = head;\n while (penultimate->next->next) penultimate = penultimate->next;\n // then we move it in the second spot\n penultimate->next->next = head->next;\n head->next = penultimate->next;\n // and set penultimate to be the last\n penultimate->next = NULL;\n // and then we proceed with the rest, same way\n reorderList(head->next->next);\n }\n};\n```\n\nThe iterative code:\n\n```cpp\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n // we need to find the penultimate node in order to proceed\n ListNode* penultimate;\n while (head && head->next && head->next->next) {\n penultimate = head;\n while (penultimate->next->next) penultimate = penultimate->next;\n // then we move it in the second spot\n penultimate->next->next = head->next;\n head->next = penultimate->next;\n // and set penultimate to be the last\n penultimate->next = NULL;\n head = head->next->next;\n }\n }\n};\n```\nCould my pride stop here? Naaaah.\n\n[Improved version with the hare-based approach](https://leetcode.com/problems/reorder-list/discuss/802983/)
| 35 | 2 |
['Linked List', 'Recursion', 'C', 'Iterator', 'C++']
| 6 |
reorder-list
|
Fast & slow find mid & reverse & merge 2 lists vs deque vs Recursion||15ms Beats 98.75%
|
fast-slow-find-mid-reverse-merge-2-lists-lmnz
|
Intuition\n Describe your first thoughts on how to solve this problem. \nSeveral days about linked lists.\nTry pure linked list solution\nOther approaches will
|
anwendeng
|
NORMAL
|
2024-03-23T01:44:21.326134+00:00
|
2024-03-23T14:08:24.548791+00:00
| 9,691 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSeveral days about linked lists.\nTry pure linked list solution\nOther approaches will be added. 2nd approach use a deque; 3rd one is a very short recursive code which is very tricky & fast.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n[Please turn English subtitles if neccessary]\n[https://youtu.be/20M4vc9rGVc?si=vUN-qvyeuDwrOe8W](https://youtu.be/20M4vc9rGVc?si=vUN-qvyeuDwrOe8W)\nusing Floyd\'s tortoise and hare algorithm.(Like in [Leetcode 234. Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/solutions/4908086/fast-slow-then-reverse-slow-vs-recursion-137ms-beats-96-66/))\n1. Set 2 pointers `slow` & `fast` with strides 1 & 2. Tranverse til `fast` reaching the end.\n\n\n2. Use the same function `reverseList` (in [ Leetcode 206. Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/solutions/4904066/beats-100-easy-reverse-linked-list-explain-with-figure/)) to reverse `slow` as `prev`\n3. Merge both lists `A=head` & `B=prev`\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# C/Python/C++ Code using Floyd\'s tortoise and hare, reverse & merge 2 lists||C++ 15ms Beats 98.75%||C 12ms\n```C []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * struct ListNode *next;\n * };\n */\n#pragma GCC optimize("O3", "unroll-loops")\ntypedef struct ListNode ListNode;\nvoid reorderList(struct ListNode* head) {\n if (!head || !head->next || !head->next->next) return;\n\n // Find the middle of the list\n ListNode *slow = head, *fast = head;\n while (fast->next && fast->next->next) {\n slow=slow->next;\n fast=fast->next->next;\n }\n\n // Reverse the second half of the list\n ListNode *prev =NULL, *cur=slow->next, *Next;\n while (cur) {\n Next=cur->next;\n cur->next=prev;\n prev=cur;\n cur=Next;\n }\n slow->next=NULL;\n\n // Merge the 2 halves\n ListNode *A = head, *B=prev;\n while (A && B) {\n ListNode* A_next=A->next;\n ListNode* B_next=B->next;\n\n A->next=B;\n B->next=A_next;\n\n A=A_next;\n B=B_next;\n } \n}\n```\n```python []\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def reorderList(self, head: Optional[ListNode]) -> None:\n """\n Do not return anything, modify head in-place instead.\n """\n if not head or not head.next or not head.next.next: return\n\n # Find the middle of the list\n slow, fast=head, head\n while fast.next and fast.next.next:\n slow=slow.next\n fast=fast.next.next\n\n # Reverse the second half of the list\n prev=None\n cur=slow.next\n while cur:\n Next=cur.next\n cur.next=prev\n prev=cur\n cur=Next\n slow.next=None\n\n # Merge the 2 halves\n A, B=head, prev\n while A and B:\n A_next=A.next\n B_next=B.next \n\n A.next=B\n B.next=A_next\n\n A=A_next\n B=B_next \n```\n```C++ []\n\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n if (!head || !head->next || !head->next->next) return;\n\n // Find the middle of the list\n ListNode *slow = head, *fast = head;\n while (fast->next && fast->next->next) {\n slow=slow->next;\n fast=fast->next->next;\n }\n\n // Reverse the second half of the list\n ListNode *prev =NULL, *cur=slow->next, *Next;\n while (cur) {\n Next=cur->next;\n cur->next=prev;\n prev=cur;\n cur=Next;\n }\n slow->next=NULL;\n\n // Merge the 2 halves\n ListNode *A = head, *B=prev;\n while (A && B) {\n ListNode* A_next=A->next;\n ListNode *B_next=B->next;\n\n A->next=B;\n B->next=A_next;\n\n A=A_next;\n B=B_next;\n }\n }\n};\n\n\nauto init = []() {\n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```\n# C++ using deque||24ms Beats 59.39%\n\nUsing container deque is easily to show the process. Let\'s consider the testcase `[1,2,3,4,5,6,7,8,9,10,11,12]`\nThe process is as follows:\n```\nCreat q from head->next on:2,3,4,5,6,7,8,9,10,11,12,\npop_back, pop_front->3,4,5,6,7,8,9,10,11,\npop_back, pop_front->4,5,6,7,8,9,10,\npop_back, pop_front->5,6,7,8,9,\npop_back, pop_front->6,7,8,\npop_back, pop_front->7,\n```\n```\nclass Solution {\npublic:\n void print(auto& q){\n for(auto& l: q) cout<<l->val<<",";\n cout<<endl;\n }\n void reorderList(ListNode* head) {\n if (!head || !head->next || !head->next->next) return;\n \n deque<ListNode*> q;\n for(ListNode* cur=head->next; cur; cur=cur->next)\n q.push_back(cur);\n // cout<<"Creat q from head->next on:";print(q);\n\n ListNode* cur=head;\n while(q.size()>=2){\n ListNode* back=q.back(), *front=q.front();\n q.pop_back();\n q.pop_front();\n\n cur->next=back;\n back->next=front;\n cur=front;\n // cout<<"pop_back, pop_front->"; print(q); \n }\n\n if (!q.empty()) {\n cur->next = q.back();\n cur->next->next = NULL;\n } \n else \n cur->next=NULL;\n q.clear();\n }\n};\n```\n# Recursive C++, python||C++ 17ms Beats 95.65%\nThe recursive solution is tricky which uses system stack. By successive recursive calling the function `transverse(right->next, cnt+1)`, in fact the `right` behaves like a backward transverse as the parameter in `transverse(ListNode* right, int cnt)`; using `n=max(n, cnt+1)` in the recursive function it can be computed the length for the list. \n\nJust see the process by uncommenting the output for testcase `[1,2,3,4,5,6,7,8,9,10,11,12]`\n(1,12) cnt=12\n(2,11) cnt=11\n(3,10) cnt=10\n(4,9) cnt=9\n(5,8) cnt=8\n(6,7) cnt=7\n```C++ []\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n ListNode* left;\n int n=0;\n void transverse(ListNode* right, int cnt){\n if (!right) return;\n n=max(n, cnt+1);\n transverse(right->next, cnt+1);\n \n if (cnt<= n/2) return;//most tricky part\n\n // cout<<"("<<left->val<<","<<right->val<< ")cnt="<<cnt<<endl;\n ListNode* Next = left->next;\n left->next = right;\n right->next = Next;\n left = Next;\n }\n\n void reorderList(ListNode* head) {\n if (!head || !head->next || !head->next->next) return;\n\n // n=1;\n // for(ListNode* cur=head; cur; cur=cur->next) n++;\n \n left=head;\n transverse(head->next, 2);\n left->next=NULL;\n }\n};\n\n```\n```python []\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def reorderList(self, head: Optional[ListNode]) -> None:\n """\n Do not return anything, modify head in-place instead.\n """\n left=None\n n=0 \n def transverse(right, cnt):\n nonlocal n, left\n if not right: return\n n=max(n, cnt+1)\n transverse(right.next, cnt+1)\n\n if cnt<=n//2: return\n\n Next=left.next\n left.next=right\n right.next=Next\n left=Next\n\n if not head or not head.next or not head.next.next: return\n left=head\n transverse(head.next, 2)\n left.next=None \n \n```\n\n
| 32 | 0 |
['Linked List', 'Two Pointers', 'Recursion', 'Queue', 'C', 'C++', 'Python3']
| 10 |
reorder-list
|
Simple JS Solution
|
simple-js-solution-by-berkansivri-290w
|
\nvar reorderList = function (head) {\n let stack = [], node = head\n if (!node) return\n while (node) {\n stack.push(node)\n node = node.next\n }\n\n
|
berkansivri
|
NORMAL
|
2019-07-28T12:41:23.315170+00:00
|
2019-07-28T12:43:14.211561+00:00
| 3,691 | false |
```\nvar reorderList = function (head) {\n let stack = [], node = head\n if (!node) return\n while (node) {\n stack.push(node)\n node = node.next\n }\n\n let len = stack.length\n node = head\n for (let i = 0; i < len; i++) {\n if (i % 2 === 0)\n node.next = stack.shift()\n else\n node.next = stack.pop()\n node = node.next\n }\n node.next = null\n};\n```
| 31 | 1 |
['JavaScript']
| 10 |
reorder-list
|
🔥BEATS 💯 % 🎯 |✨SUPER EASY BEGINNERS 👏
|
beats-super-easy-beginners-by-codewithsp-p5fe
|
\n\n---\n\n\n\n# Intuition\nTo reorder a linked list, the goal is to place the last node after the first, then the second-to-last node after the second, and so
|
CodeWithSparsh
|
NORMAL
|
2024-12-05T10:45:33.305048+00:00
|
2024-12-05T10:45:33.305095+00:00
| 2,553 | false |
\n\n---\n\n\n\n# Intuition\nTo reorder a linked list, the goal is to place the last node after the first, then the second-to-last node after the second, and so on. This can be done by splitting the list into two halves, reversing the second half, and merging them alternately. The key insight is that we only need pointers to reorder the list without creating additional structures.\n\n---\n\n# Approach\n1. **Find the middle of the list:** \n Using the slow and fast pointer technique, find the midpoint of the linked list.\n \n2. **Reverse the second half:** \n Reverse the second half of the list starting from the node after the midpoint.\n \n3. **Merge the two halves:** \n Merge the first half and the reversed second half alternately.\n\n4. **Ensure correctness in edge cases:** \n Handle cases like an empty list or a list with only one node, which don\u2019t require reordering.\n\n---\n\n# Complexity\n- **Time complexity:** \n $$O(n)$$ where \\(n\\) is the number of nodes in the linked list. Finding the middle, reversing the second half, and merging are all linear operations.\n \n- **Space complexity:** \n $$O(1)$$ as the reordering is done in-place with no additional data structures.\n\n---\n\n\n```dart []\n/**\n * Definition for singly-linked list.\n * class ListNode {\n * int val;\n * ListNode? next;\n * ListNode([this.val = 0, this.next]);\n * }\n */\nclass Solution {\n void reorderList(ListNode? head) {\n if (head == null || head.next == null) return;\n\n // Step 1: Find the middle of the list\n ListNode? slow = head, fast = head;\n while (fast != null && fast?.next != null) {\n slow = slow?.next;\n fast = fast?.next?.next;\n }\n\n // Step 2: Disconnect the first and second halves\n ListNode? secondHalf = slow?.next;\n slow?.next = null;\n\n // Step 3: Reverse the second half\n secondHalf = _reverse(secondHalf);\n\n // Step 4: Merge the two halves\n ListNode? firstHalf = head;\n while (firstHalf != null && secondHalf != null) {\n ListNode? temp1 = firstHalf.next;\n ListNode? temp2 = secondHalf.next;\n\n firstHalf.next = secondHalf;\n secondHalf.next = temp1;\n\n firstHalf = temp1;\n secondHalf = temp2;\n }\n }\n\n // Helper function to reverse a linked list\n ListNode? _reverse(ListNode? head) {\n ListNode? prev = null;\n while (head != null) {\n ListNode? next = head.next;\n head.next = prev;\n prev = head;\n head = next;\n }\n return prev;\n }\n}\n```\n\n\n```python []\nclass Solution:\n def reorderList(self, head):\n if not head or not head.next:\n return\n \n # Step 1: Find the middle of the list\n slow, fast = head, head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n \n # Step 2: Reverse the second half\n prev, curr = None, slow.next\n slow.next = None # Disconnect the two halves\n while curr:\n temp = curr.next\n curr.next = prev\n prev = curr\n curr = temp\n \n # Step 3: Merge the two halves\n first, second = head, prev\n while second:\n temp1, temp2 = first.next, second.next\n first.next = second\n second.next = temp1\n first, second = temp1, temp2\n```\n\n\n```javascript []\nvar reorderList = function(head) {\n if (!head || !head.next) return;\n\n // Step 1: Find the middle of the list\n let slow = head, fast = head;\n while (fast && fast.next) {\n slow = slow.next;\n fast = fast.next.next;\n }\n\n // Step 2: Reverse the second half\n let secondHalf = slow.next;\n slow.next = null; // Disconnect the two halves\n let prev = null;\n while (secondHalf) {\n let temp = secondHalf.next;\n secondHalf.next = prev;\n prev = secondHalf;\n secondHalf = temp;\n }\n\n // Step 3: Merge the two halves\n let firstHalf = head;\n while (prev) {\n let temp1 = firstHalf.next;\n let temp2 = prev.next;\n firstHalf.next = prev;\n prev.next = temp1;\n firstHalf = temp1;\n prev = temp2;\n }\n};\n```\n\n\n```java []\nclass Solution {\n public void reorderList(ListNode head) {\n if (head == null || head.next == null) return;\n\n // Step 1: Find the middle of the list\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n\n // Step 2: Reverse the second half\n ListNode secondHalf = slow.next;\n slow.next = null;\n ListNode prev = null;\n while (secondHalf != null) {\n ListNode temp = secondHalf.next;\n secondHalf.next = prev;\n prev = secondHalf;\n secondHalf = temp;\n }\n\n // Step 3: Merge the two halves\n ListNode firstHalf = head;\n while (prev != null) {\n ListNode temp1 = firstHalf.next;\n ListNode temp2 = prev.next;\n firstHalf.next = prev;\n prev.next = temp1;\n firstHalf = temp1;\n prev = temp2;\n }\n }\n}\n```\n\n\n```cpp []\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n if (!head || !head->next) return;\n\n // Step 1: Find the middle of the list\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) {\n slow = slow->next;\n fast = fast->next->next;\n }\n\n // Step 2: Reverse the second half\n ListNode* secondHalf = slow->next;\n slow->next = nullptr;\n ListNode* prev = nullptr;\n while (secondHalf) {\n ListNode* temp = secondHalf->next;\n secondHalf->next = prev;\n prev = secondHalf;\n secondHalf = temp;\n }\n\n // Step 3: Merge the two halves\n ListNode* firstHalf = head;\n while (prev) {\n ListNode* temp1 = firstHalf->next;\n ListNode* temp2 = prev->next;\n firstHalf->next = prev;\n prev->next = temp1;\n firstHalf = temp1;\n prev = temp2;\n }\n }\n};\n```\n\n\n```go []\nfunc reorderList(head *ListNode) {\n if head == nil || head.Next == nil {\n return\n }\n\n // Step 1: Find the middle of the list\n slow, fast := head, head\n for fast != nil && fast.Next != nil {\n slow = slow.Next\n fast = fast.Next.Next\n }\n\n // Step 2: Reverse the second half\n secondHalf := slow.Next\n slow.Next = nil\n var prev *ListNode\n for secondHalf != nil {\n temp := secondHalf.Next\n secondHalf.Next = prev\n prev = secondHalf\n secondHalf = temp\n }\n\n // Step 3: Merge the two halves\n firstHalf := head\n for prev != nil {\n temp1 := firstHalf.Next\n temp2 := prev.Next\n firstHalf.Next = prev\n prev.Next = temp1\n firstHalf = temp1\n prev = temp2\n }\n}\n```\n\n---\n\n {:style=\'width:250px\'}
| 27 | 0 |
['Linked List', 'Two Pointers', 'C', 'C++', 'Java', 'Go', 'Python3', 'JavaScript', 'Dart']
| 0 |
reorder-list
|
Modular O(N) Time and O(1) Space C++ Solution
|
modular-on-time-and-o1-space-c-solution-kvmbp
|
This was really a nice problem comprising three common smaller problems of LinkedList\n1. Find Middle Node in Linked List\n2. Reverse a Linked List\n3. Merge Tw
|
suri_kumkaran
|
NORMAL
|
2020-08-20T20:50:09.600559+00:00
|
2020-08-20T20:53:15.756062+00:00
| 1,434 | false |
This was really a nice problem comprising three common smaller problems of LinkedList\n1. Find Middle Node in Linked List\n2. Reverse a Linked List\n3. Merge Two Linked List in specific manner\n\nWe can solve all three problems in O(N) Time and O(1) Space so we can solve this problem in same Time and Space Constraints.\n\n```\nclass Solution {\npublic:\n \n ListNode* getMid(ListNode* head)\n {\n ListNode *slow,*fast;\n slow = fast = head;\n while(fast->next!=NULL&&fast->next->next!=NULL)\n {\n slow=slow->next;\n fast = fast->next->next;\n }\n return slow;\n \n }\n \n ListNode* getReverse(ListNode* head)\n {\n ListNode *cur,*prev;\n cur=head;\n prev = NULL;\n while(cur!=NULL)\n {\n ListNode *temp = cur->next;\n cur->next = prev;\n prev = cur;\n cur = temp;\n }\n return prev;\n }\n \n void reorderList(ListNode* head) {\n \n // If Linked List contains less than 3 nodes then no need to do anything.\n if(head==NULL||head->next==NULL||head->next->next==NULL)\n return;\n \n /* \n Get Middle Node\n If there is two middle node then return first Middle.\n */\n ListNode* mid = getMid(head);\n \n // Seprate the Second Half of the LinkedList\n ListNode* secondHalf = mid->next;\n mid->next=NULL;\n \n // Reverse the Second Half of LinkedList\n ListNode* revHalf = getReverse(secondHalf);\n \n // Finally Merge in Required Manner\n while(head!=NULL&&revHalf!=NULL)\n {\n ListNode* temp = head->next;\n head->next=revHalf;\n revHalf=revHalf->next;\n head->next->next=temp;\n head = temp;\n }\n }\n};\n```
| 27 | 1 |
['C']
| 3 |
reorder-list
|
My O(n) C++ Method, accepted
|
my-on-c-method-accepted-by-linwish-027m
|
Firstly, I split the list from the middle into two lists. One from head to middle, and the other from middle to the end. Then we reverse the second list. Finall
|
linwish
|
NORMAL
|
2014-10-15T03:01:08+00:00
|
2018-09-03T20:52:27.234712+00:00
| 12,677 | false |
Firstly, I split the list from the middle into two lists. One from head to middle, and the other from middle to the end. Then we reverse the second list. Finally we merge these two lists. O(n) time complexity and O(1) space complexity. \n\n /**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode(int x) : val(x), next(NULL) {}\n * };\n */\n class Solution {\n public:\n void reorderList(ListNode *head) {\n if(head == NULL || head->next == NULL || head->next->next==NULL)\n return;\n //find the middle of the list, and split into two lists. \n ListNode *p=head,*q=head;\n while(p && q && q->next && q->next->next){\n p=p->next;\n q=q->next->next;\n }\n \n ListNode *mid = p->next;\n p->next=NULL;\n p=head;\n //reverse from the middle to the end\n ListNode *q1=mid, *q2,*q3;\n if(mid->next){\n q1=mid;\n q2=mid->next;\n while(q2){\n q3=q2->next;\n q2->next=q1;\n q1=q2;\n q2=q3;\n \n }\n mid->next=NULL;\n }\n q=q1;\n //merge these two list\n ListNode *s=p;\n p=p->next;\n while(p && q){\n s->next=q;\n s=s->next;\n q=q->next;\n \n s->next=p;\n s=s->next;\n p=p->next;\n }\n if(p){\n s->next=p;\n }\n if(q){\n s->next=q;\n }\n }\n };
| 27 | 1 |
[]
| 8 |
reorder-list
|
Easy C++ solution | TC: O(n) , SC: O(1)
|
easy-c-solution-tc-on-sc-o1-by-priyal04-w9mh
|
Step 1: Find the middle node of linked list by slow and fast pointer technique.\nStep 2: Divide the linked list into 2 , one from start to mid and second from
|
priyal04
|
NORMAL
|
2021-12-22T08:14:41.147529+00:00
|
2021-12-22T08:14:41.147566+00:00
| 1,445 | false |
**Step 1**: Find the middle node of linked list by slow and fast pointer technique.\n**Step 2**: Divide the linked list into 2 , one from start to mid and second from mid+1 to end.\n**Step 3**: Reverse the second linked list.\n**Step 4**: At last, Merge the 2 linked list.\n\n```\nclass Solution {\n ListNode* reverse(ListNode* head){\n ListNode* prev = NULL;\n ListNode* curr = head;\n ListNode* nexxt;\n \n while(curr){\n nexxt = curr->next;\n curr->next = prev;\n prev = curr;\n curr = nexxt;\n }\n return prev;\n }\n \npublic:\n void reorderList(ListNode* head) {\n //base case\n if(!head || !(head->next) || !(head->next->next)) return;\n \n //Step1: Find middle node (in case of even length, find first middle node)\n ListNode* slow = head;\n ListNode* fast = head->next;\n \n while(fast and fast->next){\n fast = fast->next->next;\n slow = slow->next;\n }\n \n\t\t//break linked list into 2 (first from start to mid and second from mid+1 to end)\n ListNode* head2 = slow->next;\n slow->next = NULL;\n \n //Step2: Reverse linked list 2 (from mid+1 to end)\n head2 = reverse(head2);\n \n //Step3: Merge 2 linked lists\n ListNode* h = head;\n while(head2){\n ListNode* temp = head2->next;\n head2->next = h->next;\n h ->next = head2;\n head2 = temp;\n h = h->next->next;\n }\n }\n};\n```\n\n**Time Complexity: O(n)** \nO(n/2) to find middle node + O(n/2) to reverse second linked list + O(n/2) to merge 2 list = O(n)\n**Space Complexity: O(1)**\n\n***Please Upvote, if you find the solution helpful.\nHappy Coding!***
| 26 | 0 |
['C']
| 2 |
reorder-list
|
C++ easy clean code with explaination | O(n) time and O(1) space
|
c-easy-clean-code-with-explaination-on-t-97ir
|
This problem can be broken down into three simple sub problems and can be solve sequentially to arrive at our final solution.\n1. Finding the mid: take slow and
|
anchal_soni
|
NORMAL
|
2021-10-03T12:10:26.427050+00:00
|
2021-10-03T12:10:26.427082+00:00
| 1,693 | false |
This problem can be broken down into three simple sub problems and can be solve sequentially to arrive at our final solution.\n**1. Finding the mid:** take slow and fast ptr and find the start of the second half of Linked List\n**2. Reverse Linked List:** reverse the second half and split the original Linked list into two independent linked list\n**3. Merge Linked List:** take each node one by one from both the sublists and merge them into single linked list.\n```\nclass Solution {\npublic:\n ListNode* reverse(ListNode* head)\n {\n ListNode* prev=NULL;\n ListNode* curr=head;\n ListNode* nxt=NULL;\n \n while(curr)\n {\n nxt=curr->next;\n curr->next=prev;\n prev=curr;\n curr=nxt;\n }\n return prev;\n }\n \n void reorderList(ListNode* head) {\n \n //step 1 - using slow and fast pointer approach to find the mid of the list\n ListNode* slow=head;\n ListNode* fast=head->next;\n \n while(fast and fast->next)\n {\n slow=slow->next;\n fast=fast->next->next;\n }\n \n //step 2 - reverse the second half and split the List into two.\n ListNode* second=reverse(slow->next); // independent list second\n slow->next=NULL;\n ListNode* first=head; // independent list first\n \n //step 3 - merging the two list\n // second list can be shorter when LL size is odd\n while(second)\n {\n ListNode* temp1=first->next;\n ListNode* temp2=second->next;\n first->next=second;\n second->next=temp1;\n first=temp1;\n second=temp2;\n }\n }\n};\n```\nExample:\n**A. for odd length List**\n1, 2, 3, 4, 5\nslow ptr= 3\nreverse(4)\nsublist1 = 1, 2, 3\nsublist2 = 5, 4\nafter merge 1, 5, 2, 4, 3\n\n**B, for even length List**\n1, 2, 3, 4\nslow ptr= 2\nreverse(3)\nsublist1 = 1, 2\nsublist2 = 4, 3\nafter merge 1, 4, 2, 3
| 26 | 0 |
['C', 'C++']
| 1 |
reorder-list
|
Java | Algo explained | beats 100% time
|
java-algo-explained-beats-100-time-by-lo-1y6k
|
\nEXPLANATION:-\nGiven a list 1 -> 2 -> 3 -> 4 -> 5\nNow we need to reorder it like 1 -> 5 -> 2 -> 4 -> 3\n\nHow can we do this?\nconsider list elements as L1
|
logan138
|
NORMAL
|
2020-08-20T07:24:39.014903+00:00
|
2024-09-26T10:37:25.833846+00:00
| 1,744 | false |
```\nEXPLANATION:-\nGiven a list 1 -> 2 -> 3 -> 4 -> 5\nNow we need to reorder it like 1 -> 5 -> 2 -> 4 -> 3\n\nHow can we do this?\nconsider list elements as L1, L2, .... , Ln-1, Ln.\nwe need \nL1 -> Ln -> L2 -> Ln-1 -> . . .\nNow, if we maintain a pointer at each end, \nthen we can arrange them alternatively.\nleft = L1, right = Ln\nNow 1st iteration\nList => L1 -> Ln\n\n2nd iteration\nleft = L2, right = Ln-1\nList => L1 -> Ln -> L2 -> Ln-1\n\n3rd iteration\nleft = l3, right = Ln-2\nThis process continues until all elements are processed.\n\nHere, the problem is if we maintain a pointer at last element in the list\nwe can\'t move to it\'s previous element after \nit is processed since it is single linked list.\n\nSo, to do this, we split the list in two halves and \nreverse the second half.\nList = 1 -> 2 -> 3 > 4 -> 5\nAfter splitting:-\nL1 = 1 -> 2\nL2 = 3 -> 4 -> 5\nNow, we need to reverse second list\nSo, L2 = 5 -> 4 -> 3\n\nNow, insert each element in 2 lists alternatively.\n1 -> 5 -> 2 -> 4 -> 3\n\nThis is how we can get the result.\n\nIF YOU HAVE ANY DOUBTS, FEEL FREE TO ASK.\nIF YOU UNDERSTAND, DON\'T FORGET TO UPVOTE.\n\n\n```\n```\nclass Solution {\n public ListNode reverse(ListNode head){\n ListNode p1 = head;\n ListNode p2 = head.next;\n p1.next = null;\n while(p2 != null){\n ListNode temp = p2.next;\n p2.next = p1;\n p1 = p2;\n p2 = temp;\n }\n return p1;\n }\n public void reorderList(ListNode head) {\n if(head == null || head.next == null) return ;\n ListNode slowPtr = head, fastPtr = head;\n ListNode prev = head;\n\t\t// splitting list\n while(fastPtr != null && fastPtr.next != null){\n prev = slowPtr;\n slowPtr = slowPtr.next;\n fastPtr = fastPtr.next.next;\n }\n prev.next = null;\n\t\t// reverse\n ListNode rev = reverse(slowPtr);\n ListNode ptr = head;\n\t\t// arrange alternatively\n while(ptr != null){\n ListNode t1 = ptr.next;\n ListNode t2 = rev.next;\n ptr.next = rev;\n if(t1 != null)\n rev.next = t1;\n ptr = t1;\n rev = t2;\n }\n }\n}\n```\n\nI have started a series on solid principles and design patterns. If anyone is interested, please check [it](https://medium.com/@bhanu150138/mastering-solid-principles-and-design-patterns-a-blog-series-for-writing-clean-scalable-code-aae3809310db) out.
| 25 | 1 |
['Linked List', 'Two Pointers', 'Stack', 'Recursion']
| 7 |
reorder-list
|
JAVA || Stack || Easy Solution with explanation
|
java-stack-easy-solution-with-explanatio-rumq
|
\n\n\n\n\nclass Solution \n{\n public void reorderList(ListNode head) \n {\n int n=0;\n Stack<ListNode> track=new Stack<>();\n ListNode temp=head;\n \n while(temp != null)\n {\n track.push(temp);//pushing the node into the stack \n temp=temp.next;\n n+=1;//counting the length \n }\n \n temp=head;\n \n for (int i=0; i<n/2;i++)//traversing to only the half length \n {\n ListNode str=temp.next;//storing the next node \n \n temp.next=track.peek();//current node pointing to the next node \n track.pop().next=str;//maintaining the link \n \n temp=temp.next.next;//as the pair consist of 2, we are covering 2 node at a time \n }\n \n temp.next = null;//to remove the cycle or the cyclic dependency of the elements\n }\n}//Please do vote me, It helps a lot\n```
| 23 | 0 |
['Stack', 'Java']
| 1 |
reorder-list
|
Intuitive JavaScript Solution
|
intuitive-javascript-solution-by-dawchih-iyw5
|
\n/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode
|
dawchihliou
|
NORMAL
|
2020-04-21T06:41:07.523049+00:00
|
2020-04-21T06:41:07.523099+00:00
| 4,007 | false |
```\n/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} head\n * @return {void} Do not return anything, modify head in-place instead.\n */\nvar reorderList = function(head) {\n if (head === null) {\n return;\n }\n /**\n * The goal is to reverse the second half of the list and merge it onto\n * the first half of the list. The first half will have at most one more\n * element than the second half.\n */\n let second = split(head);\n second = reverse(second);\n merge(head, second);\n};\n\nfunction split(node) {\n let fast = node;\n let slow = node;\n \n while (fast !== null) {\n if (fast.next !== null && fast.next.next !== null) {\n slow = slow.next;\n fast = fast.next.next;\n } else {\n fast = null;\n }\n }\n \n const secondHalf = slow.next;\n slow.next = null;\n \n return secondHalf;\n}\n\nfunction reverse(node) {\n let curr = node;\n let prev = null;\n let next = null;\n \n while (curr !== null) {\n next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n \n return prev;\n}\n\nfunction merge (l1, l2) {\n let l1Next = null;\n let l2Next = null;\n \n while(l2 !== null) {\n l1Next = l1.next;\n l2Next = l2.next;\n \n l1.next = l2;\n l2.next = l1Next;\n \n l1 = l1Next;\n l2 = l2Next;\n }\n}\n```
| 22 | 1 |
['Iterator', 'JavaScript']
| 1 |
reorder-list
|
Interview Approach | 4 Approaches
|
interview-approach-4-approaches-by-cs_ii-xueo
|
Subscribe to my channel\n\nBefore moving ahead, please read the yesterday\'s solution.\nI am reusing the 4th approach\n234. Palindrome Linked List\n\n# Approach
|
cs_iitian
|
NORMAL
|
2023-11-05T02:15:07.041192+00:00
|
2024-03-23T17:33:31.796528+00:00
| 1,737 | false |
[Subscribe to my channel](https://www.youtube.com/channel/UCuxmikkhqbmBOUVxf-61hxw)\n\nBefore moving ahead, please read the yesterday\'s solution.\nI am reusing the 4th approach\n[234. Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/solutions/4908031/interview-approach-4-approach-list-stack-recursion-two-pointer-approach/)\n\n# Approach#1 ( Using List )\n\nSo as I told every Linked List problem can be done via array as well, I mena copy the content in array and solve it as it was an array and then update the list.\nHere also I could do the same, I will create array and then alternatively will replace values into linked list.\n\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n vector<int> list;\n ListNode* curr = head;\n while (curr != nullptr) {\n list.push_back(curr->val);\n curr = curr->next;\n }\n\n curr = head;\n for (int i = 0; i < list.size(); ++i) {\n curr->val = list[i%2 == 0 ? i/2 : list.size()-(i+1)/2];\n curr = curr->next;\n }\n }\n};\n```\n```Java []\nclass Solution {\n public void reorderList(ListNode head) {\n List<Integer> list = new ArrayList();\n ListNode curr = head;\n while(curr != null) {\n list.add(curr.val);\n curr = curr.next;\n }\n for(int i=0;i<list.size();i++) {\n head.val = list.get(i%2 == 0 ? i/2 : list.size()-(i+1)/2);\n head = head.next;\n }\n }\n}\n```\n```Python3 []\nclass Solution:\n def reorderList(self, head: Optional[ListNode]) -> None:\n list_values = []\n curr = head\n while curr:\n list_values.append(curr.val)\n curr = curr.next\n \n # Reorder the list using for loop\n curr = head\n for i in range(len(list_values)):\n if i % 2 == 0:\n curr.val = list_values[i // 2]\n else:\n curr.val = list_values[len(list_values) - (i + 1) // 2]\n curr = curr.next\n```\n```JavaScript []\nvar reorderList = function(head) {\n const list = [];\n let curr = head;\n while (curr !== null) {\n list.push(curr.val);\n curr = curr.next;\n }\n\n curr = head;\n for (let i = 0; i < list.length; i++) {\n if (i % 2 === 0) {\n curr.val = list[Math.floor(i / 2)];\n } else {\n curr.val = list[list.length - Math.floor((i + 1) / 2)];\n }\n curr = curr.next;\n }\n};\n```\n\n# Approach#2 ( Using Recursion )\nfor each node , find last node and re-arrange it and then move to next node.\n\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n helper(head);\n }\n\n ListNode* helper(ListNode* head) {\n if (head == nullptr || head->next == nullptr) return head;\n ListNode* last = head;\n ListNode* prev = head;\n while (last->next != nullptr) {\n prev = last;\n last = last->next;\n }\n prev->next = nullptr;\n ListNode* next = head->next;\n head->next = last;\n last->next = helper(next);\n return head;\n }\n};\n```\n```Java []\nclass Solution {\n public void reorderList(ListNode head) {\n helper(head);\n }\n\n public ListNode helper(ListNode head) {\n if(head == null || head.next == null) return head;\n ListNode last = head;\n ListNode prev = head;\n while(last.next != null) {\n prev = last;\n last = last.next;\n }\n prev.next = null;\n ListNode next = head.next;\n head.next = last;\n last.next = solve(next);\n return head;\n }\n}\n```\n```Python3 []\nclass Solution:\n def reorderList(self, head: Optional[ListNode]) -> None:\n self.helper(head)\n\n def helper(self, head: Optional[ListNode]) -> ListNode:\n if head is None or head.next is None:\n return head\n last = head\n prev = head\n while last.next:\n prev = last\n last = last.next\n prev.next = None\n next_node = head.next\n head.next = last\n last.next = self.helper(next_node)\n return head\n```\n```Javascript []\nvar reorderList = function(head) {\n helper(head);\n};\n\nvar helper = function(head) {\n if (head === null || head.next === null) {\n return head;\n }\n let last = head;\n let prev = head;\n while (last.next !== null) {\n prev = last;\n last = last.next;\n }\n prev.next = null;\n const next = head.next;\n head.next = last;\n last.next = helper(next);\n return head;\n};\n```\n\n# Approach#3 ( Recursion - Only Smart A** can understand )\nJust think of like you know that end of the linked list is always middle and next middle. then we can append at the start previous of middle with next of next middle and so on.\n\nI think you didn\'t understand this, let me draw for you.\nDraft: ( I will draw here and will update code for other languages , till then you can try to think like how it\'s possible , Take your time. )\n\n\n\n\n# Code\n```Java []\nclass Solution {\n public void reorderList(ListNode head) {\n helper(head, head.next);\n }\n\n public ListNode[] helper(ListNode slow, ListNode fast) {\n if(fast == null || fast.next == null) \n return new ListNode[]{slow, fast == null ? slow : slow.next};\n ListNode[] ret = helper(slow.next, fast.next.next);\n ListNode next = ret[1].next;\n if(ret[1].next != null) ret[1].next = ret[1].next.next;\n slow.next = next;\n if(next != null) next.next = ret[0];\n return new ListNode[]{slow, ret[1]};\n }\n}\n```\n\n# Approach#4 ( Like Palindrome Linked List )\n<!-- Describe your first thoughts on how to solve this problem. -->\nSo Basically\nL0 -> LN -> L1 -> LN-1 .....\nDid you find any similarity between palindrome linked list and this one, if yes congratulations you made this problem easy.\n\n```Steps []\n- first find middle node\n- reverse the second half\n- now merge first and second half alternatively\n```\n\n\n\n# Complexity\n- Time complexity: O(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```C++ []\nclass Solution {\npublic:\n ListNode* reverse(ListNode* head) {\n ListNode* prev = nullptr;\n ListNode* curr = head;\n while (curr != nullptr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n }\n\n void reorderList(ListNode* head) {\n if (head == nullptr) return;\n\n ListNode* slow = head;\n ListNode* fast = head->next;\n while (fast != nullptr && fast->next != nullptr) {\n slow = slow->next;\n fast = fast->next->next;\n }\n\n ListNode* rev = reverse(slow->next);\n slow->next = nullptr;\n\n while (rev != nullptr) {\n ListNode* headNext = head->next;\n ListNode* revNext = rev->next;\n head->next = rev;\n rev->next = headNext;\n head = headNext;\n rev = revNext;\n }\n }\n};\n```\n```Java []\nclass Solution {\n public ListNode reverse(ListNode head) {\n ListNode prev = null;\n ListNode curr = head;\n while(curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n }\n\n public void reorderList(ListNode head) {\n ListNode slow = head;\n ListNode fast = head.next;\n while(fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n ListNode rev = reverse(slow.next); // reverse second list\n slow.next = null;\n\n // now add node one by one\n while(rev != null) {\n ListNode headNext = head.next;\n ListNode revNext = rev.next;\n head.next = rev;\n rev.next = headNext;\n head = headNext;\n rev = revNext;\n }\n }\n}\n```\n```Python3 []\nclass Solution:\n def reverse(self, head: ListNode) -> ListNode:\n prev = None\n curr = head\n while curr:\n next_temp = curr.next\n curr.next = prev\n prev = curr\n curr = next_temp\n return prev\n\n def reorderList(self, head: Optional[ListNode]) -> None:\n if head is None:\n return\n\n # Find the middle of the list\n slow = head\n fast = head.next\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n\n # Reverse the second half\n rev = self.reverse(slow.next)\n slow.next = None\n\n # Reorder one by one\n while rev:\n head_next = head.next\n rev_next = rev.next\n head.next = rev\n rev.next = head_next\n head = head_next\n rev = rev_next\n```\n```Javascript []\nvar reverse = function(head) {\n let prev = null;\n let curr = head;\n while (curr !== null) {\n let nextTemp = curr.next;\n curr.next = prev;\n prev = curr;\n curr = nextTemp;\n }\n return prev;\n}\n\nvar reorderList = function(head) {\n if (!head) return;\n\n let slow = head;\n let fast = head.next;\n while (fast && fast.next) {\n slow = slow.next;\n fast = fast.next.next;\n }\n\n let rev = reverse(slow.next);\n slow.next = null;\n\n while (rev) {\n let headNext = head.next;\n let revNext = rev.next;\n head.next = rev;\n rev.next = headNext;\n head = headNext;\n rev = revNext;\n }\n};\n```\n\nIf you like this post, please upvote it.
| 21 | 0 |
['C++', 'Java', 'Python3', 'JavaScript']
| 8 |
reorder-list
|
✔️ 100% Fastest Swift Solution, time: O(n), space: O(1).
|
100-fastest-swift-solution-time-on-space-zdde
|
\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * public var val: Int\n * public var next: ListNode?\n * public init() {
|
sergeyleschev
|
NORMAL
|
2022-04-13T05:45:16.832718+00:00
|
2022-04-13T05:45:16.832764+00:00
| 816 | false |
```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * public var val: Int\n * public var next: ListNode?\n * public init() { self.val = 0; self.next = nil; }\n * public init(_ val: Int) { self.val = val; self.next = nil; }\n * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }\n * }\n */\nclass Solution {\n // - Complexity:\n // - time: O(n), where n is the number of nodes in the linked list.\n // - space: O(1), only constant space is used.\n \n func reorderList(_ head: ListNode?) {\n guard head != nil else { return }\n\n var slow = head\n var fast = head\n\n while fast?.next != nil {\n slow = slow?.next\n fast = fast?.next?.next\n }\n\n let reversedList = reverseList(slow)\n mergeLists(head, reversedList)\n }\n \n\n private func reverseList(_ head: ListNode?) -> ListNode? {\n var prev: ListNode? = nil\n var curr = head\n var next: ListNode? = nil\n\n while curr != nil {\n next = curr?.next\n\n curr?.next = prev\n prev = curr\n curr = next\n }\n\n return prev\n }\n \n\n private func mergeLists(_ first: ListNode?, _ second: ListNode?) {\n var first = first\n var second = second\n var tmp: ListNode? = nil\n\n while second?.next != nil {\n tmp = first?.next\n first?.next = second\n first = tmp\n\n tmp = second?.next\n second?.next = first\n second = tmp\n }\n }\n\n}\n```\n\nLet me know in comments if you have any doubts. I will be happy to answer.\n\nPlease upvote if you found the solution useful.
| 20 | 0 |
['Swift']
| 0 |
reorder-list
|
3-step Space-efficient Javascript Solution
|
3-step-space-efficient-javascript-soluti-res9
|
Recommended prerequisite: https://leetcode.com/problems/reverse-linked-list/\n\n\n/**\n * @param {ListNode} head\n * @return {void} Do not return anything, modi
|
barbariansyah
|
NORMAL
|
2022-01-31T13:57:05.372945+00:00
|
2022-01-31T13:57:05.372989+00:00
| 2,912 | false |
Recommended prerequisite: https://leetcode.com/problems/reverse-linked-list/\n\n```\n/**\n * @param {ListNode} head\n * @return {void} Do not return anything, modify head in-place instead.\n */\nvar reorderList = function(head) {\n // find middle\n\t// by moving "fast" twice, we\'ll have "slow" in the middle\n let slow = head\n let fast = head\n while (fast.next && fast.next.next) {\n slow = slow.next\n fast = fast.next.next\n }\n\n // reverse second half\n\t// with reverse linked list solution\n let prev = null\n let cur = slow.next\n while (cur) {\n let temp = cur.next\n cur.next = prev\n prev = cur\n cur = temp\n }\n\n slow.next = null\n\n // combine two halves\n let h1 = head\n let h2 = prev\n\n // if even, second half will be smaller\n\twhile (h2) {\n let temp = h1.next\n h1.next = h2\n h1 = h2\n h2 = temp\n }\n};\n```\n\nexample run:\n```\nhead: 1 -> 2 -> 3 -> 4 -> 5\n\nh1: 1 -> 2 -> 3\nh2: 5 -> 4\n\nhead: 1 -> 5 -> 2 -> 4 -> 3\n```
| 20 | 0 |
['JavaScript']
| 3 |
reorder-list
|
Beats 100% || Full Code Explained || [java/C++/C#/Python/JavaScript]
|
beats-100-full-code-explained-javaccpyth-5ikz
|
Intution\n1. We just need to know how to find middle of the linkedList, and reverse the linkedList.\n2. Now follow the visualization section, you will understan
|
Shivansu_7
|
NORMAL
|
2024-03-23T08:19:31.302895+00:00
|
2024-03-23T08:19:31.302923+00:00
| 2,850 | false |
# Intution\n1. We just need to know how to find middle of the linkedList, and reverse the linkedList.\n2. Now follow the visualization section, you will understand the whole process.\n\n# Visualization.\n1. ***Finding the middle of the LinkedList.***\n\n\n2. ***Reverse The Second Half.***\n\n\n3. ***Merge both the LinkedList.***\n\n\n\n# Approach\n### Step 1: Finding the Middle Node\n- The `midNode` function is used to locate the middle node of the linked list.\n- It utilizes the slow and fast pointer technique.\n- The slow pointer moves one step at a time while the fast pointer moves two steps at a time.\n- When the fast pointer reaches the end of the list, the slow pointer points to the middle node.\n\n### Step 2: Reversing the Second Half\n- After finding the middle node, the second half of the list starting from the node after the middle is reversed.\n- This is achieved using the `reverseLinkedList` function, which reverses the direction of the nodes in the second half of the list.\n\n### Step 3: Reordering the List\n- Once the list is divided and the second half is reversed, the `reorderList` function merges the two halves alternately.\n- Two pointers (`c1` and `c2`) are used to traverse the two halves simultaneously.\n- While both pointers are not null, nodes from each half are linked alternately.\n- Backup nodes are used to prevent losing the next nodes during reordering.\n- This process continues until all nodes are reordered.\n\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(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```Java []\nclass Solution {\n public void reorderList(ListNode head) {\n if(head==null || head.next==null) {\n return;\n }\n\n ListNode middle = midNode(head);\n ListNode newHead = middle.next;\n middle.next = null;\n\n newHead = reverseLinkedList(newHead);\n\n ListNode c1 = head;\n ListNode c2 = newHead;\n ListNode f1 = null;\n ListNode f2 = null;\n\n while(c1 != null && c2 != null) {\n\n // Backup\n f1 = c1.next;\n f2 = c2.next;\n\n //Linking\n c1.next = c2;\n c2.next = f1;\n\n // Move\n c1 = f1;\n c2 = f2;\n }\n }\n\n private ListNode midNode(ListNode head) {\n ListNode slow = head;\n ListNode fast = head;\n\n while(fast.next!=null && fast.next.next!=null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n }\n\n private ListNode reverseLinkedList(ListNode head) {\n ListNode prev = null;\n ListNode curr = head;\n ListNode forw = null;\n\n while(curr != null) {\n forw = curr.next;\n curr.next = prev;\n prev = curr;\n curr = forw;\n }\n return prev;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n if (!head || !head->next) {\n return;\n }\n\n ListNode* middle = midNode(head);\n ListNode* newHead = middle->next;\n middle->next = nullptr;\n\n newHead = reverseLinkedList(newHead);\n\n ListNode* c1 = head;\n ListNode* c2 = newHead;\n ListNode* f1 = nullptr;\n ListNode* f2 = nullptr;\n\n while (c1 && c2) {\n // Backup\n f1 = c1->next;\n f2 = c2->next;\n\n // Linking\n c1->next = c2;\n c2->next = f1;\n\n // Move\n c1 = f1;\n c2 = f2;\n }\n }\n\nprivate:\n ListNode* midNode(ListNode* head) {\n ListNode* slow = head;\n ListNode* fast = head;\n\n while (fast->next && fast->next->next) {\n slow = slow->next;\n fast = fast->next->next;\n }\n return slow;\n }\n\n ListNode* reverseLinkedList(ListNode* head) {\n ListNode* prev = nullptr;\n ListNode* curr = head;\n ListNode* forw = nullptr;\n\n while (curr) {\n forw = curr->next;\n curr->next = prev;\n prev = curr;\n curr = forw;\n }\n return prev;\n }\n};\n```\n```Python3 []\nclass Solution:\n def reorderList(self, head: ListNode) -> None:\n if not head or not head.next:\n return\n\n middle = self.midNode(head)\n new_head = middle.next\n middle.next = None\n\n new_head = self.reverseLinkedList(new_head)\n\n c1 = head\n c2 = new_head\n f1 = None\n f2 = None\n\n while c1 and c2:\n # Backup\n f1 = c1.next\n f2 = c2.next\n\n # Linking\n c1.next = c2\n c2.next = f1\n\n # Move\n c1 = f1\n c2 = f2\n\n def midNode(self, head: ListNode) -> ListNode:\n slow = head\n fast = head\n\n while fast.next and fast.next.next:\n slow = slow.next\n fast = fast.next.next\n return slow\n\n def reverseLinkedList(self, head: ListNode) -> ListNode:\n prev = None\n curr = head\n\n while curr:\n forw = curr.next\n curr.next = prev\n prev = curr\n curr = forw\n return prev\n```\n```Go []\nfunc reorderList(head *ListNode) {\n if head == nil || head.Next == nil {\n return\n }\n\n middle := midNode(head)\n newHead := middle.Next\n middle.Next = nil\n\n newHead = reverseLinkedList(newHead)\n\n c1 := head\n c2 := newHead\n var f1, f2 *ListNode\n\n for c1 != nil && c2 != nil {\n // Backup\n f1 = c1.Next\n f2 = c2.Next\n\n // Linking\n c1.Next = c2\n c2.Next = f1\n\n // Move\n c1 = f1\n c2 = f2\n }\n}\n\nfunc midNode(head *ListNode) *ListNode {\n slow := head\n fast := head\n\n for fast.Next != nil && fast.Next.Next != nil {\n slow = slow.Next\n fast = fast.Next.Next\n }\n return slow\n}\n\nfunc reverseLinkedList(head *ListNode) *ListNode {\n var prev, curr, forw *ListNode = nil, head, nil\n\n for curr != nil {\n forw = curr.Next\n curr.Next = prev\n prev = curr\n curr = forw\n }\n return prev\n}\n```\n```C# []\npublic class Solution {\n public void ReorderList(ListNode head) {\n if (head == null || head.next == null) {\n return;\n }\n\n ListNode middle = MidNode(head);\n ListNode newHead = middle.next;\n middle.next = null;\n\n newHead = ReverseLinkedList(newHead);\n\n ListNode c1 = head;\n ListNode c2 = newHead;\n ListNode f1 = null;\n ListNode f2 = null;\n\n while (c1 != null && c2 != null) {\n // Backup\n f1 = c1.next;\n f2 = c2.next;\n\n // Linking\n c1.next = c2;\n c2.next = f1;\n\n // Move\n c1 = f1;\n c2 = f2;\n }\n }\n\n private ListNode MidNode(ListNode head) {\n ListNode slow = head;\n ListNode fast = head;\n\n while (fast.next != null && fast.next.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n }\n\n private ListNode ReverseLinkedList(ListNode head) {\n ListNode prev = null;\n ListNode curr = head;\n ListNode forw = null;\n\n while (curr != null) {\n forw = curr.next;\n curr.next = prev;\n prev = curr;\n curr = forw;\n }\n return prev;\n }\n}\n```\n```JavaScript []\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n\n/**\n * @param {ListNode} head\n * @return {void} Do not return anything, modify head in-place instead.\n */\nvar reorderList = function(head) {\n if (!head || !head.next) {\n return;\n }\n\n const middle = midNode(head);\n let newHead = middle.next;\n middle.next = null;\n\n newHead = reverseLinkedList(newHead);\n\n let c1 = head;\n let c2 = newHead;\n let f1 = null;\n let f2 = null;\n\n while (c1 && c2) {\n // Backup\n f1 = c1.next;\n f2 = c2.next;\n\n // Linking\n c1.next = c2;\n c2.next = f1;\n\n // Move\n c1 = f1;\n c2 = f2;\n }\n};\n\nconst midNode = function(head) {\n let slow = head;\n let fast = head;\n\n while (fast.next && fast.next.next) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n};\n\nconst reverseLinkedList = function(head) {\n let prev = null;\n let curr = head;\n let forw = null;\n\n while (curr) {\n forw = curr.next;\n curr.next = prev;\n prev = curr;\n curr = forw;\n }\n return prev;\n};\n```\n\n---\n\n### ***FEEL FREE TO GIVE SOME OTHER APROACHES, AND OPTIMIZE MY APPROACH***\n\n---\n\n\n
| 18 | 0 |
['Python', 'C++', 'Java', 'Go', 'Python3', 'JavaScript', 'C#']
| 5 |
reorder-list
|
Python solution
|
python-solution-by-fangkunjnsy-4lr2
|
Does't matter if the length of the list is odd or even, find mid, split, reverse the second list and insert. Pretty straightfowward.\n\n class Solution(objec
|
fangkunjnsy
|
NORMAL
|
2015-10-18T07:16:35+00:00
|
2018-10-20T03:40:51.358615+00:00
| 4,276 | false |
Does't matter if the length of the list is odd or even, find mid, split, reverse the second list and insert. Pretty straightfowward.\n\n class Solution(object):\n def reorderList(self, head):\n if not head or not head.next or not head.next.next: return\n slow, fast=head, head\n while fast.next and fast.next.next: slow, fast=slow.next, fast.next.next\n head1, head2=head, slow.next\n slow.next, cur, pre=None, head2, None\n while cur:\n curnext=cur.next\n cur.next=pre\n pre=cur\n cur=curnext\n cur1, cur2=head1, pre\n while cur2:\n next1, next2=cur1.next, cur2.next\n cur1.next=cur2\n cur2.next=next1\n cur1, cur2=next1, next2
| 17 | 0 |
[]
| 6 |
reorder-list
|
[Beats 100% 🔥] Beginner Friendly Easy to Understand Explanation 🚀
|
beats-100-beginner-friendly-easy-to-unde-wi0j
|
IntuitionTo reorder the linked list, we need to place the last node after the first, the second-last after the second, and so on. We can achieve this by breakin
|
PradhumanGupta
|
NORMAL
|
2025-02-15T08:16:00.435694+00:00
|
2025-02-15T08:16:00.435694+00:00
| 1,219 | false |
# Intuition
To reorder the linked list, we need to place the last node after the first, the second-last after the second, and so on. We can achieve this by breaking the list into two halves, reversing the second half, and merging them alternately.
# Approach
1. **Find the Middle:**
- Use slow and fast pointers to locate the middle of the list.
- Split the list into two halves by setting `prev.next = null`.
2. **Reverse the Second Half:**
- Reverse the second half of the list in-place.
3. **Merge Both Halves Alternately:**
- Merge nodes from both halves one by one to form the reordered list.
# Complexity
- **Time complexity:** $$O(N)$$ – Finding the middle, reversing, and merging each take linear time.
- **Space complexity:** $$O(1)$$ – No extra space used; modifications are done in-place.
# Code
```java []
class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null || head.next.next == null) return;
// Step 1: Find the middle of the list
ListNode slow = head, fast = head, prev = null;
while (fast != null && fast.next != null) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = null; // Split the list into two halves
// Step 2: Reverse the second half
ListNode secondHalf = reverseList(slow);
// Step 3: Merge both halves alternately
mergeLists(head, secondHalf);
}
private ListNode reverseList(ListNode head) {
ListNode prev = null, curr = head, next;
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev; // New head of the reversed list
}
private void mergeLists(ListNode first, ListNode second) {
while (first != null && second != null) {
ListNode temp1 = first.next;
ListNode temp2 = second.next;
first.next = second;
if (temp1 == null) break;
second.next = temp1;
first = temp1;
second = temp2;
}
}
}
```
**Please Upvote⬆️**

| 16 | 0 |
['Linked List', 'Two Pointers', 'Sorting', 'Java']
| 1 |
reorder-list
|
My C++ code (split, reverse the second half, and merge), 71 ms
|
my-c-code-split-reverse-the-second-half-yqs93
|
The basic idea is to split the list in half, then reverse the second half, and at last merge them. It is O(n) time, O(1) space. I was also wondering if there i
|
lejas
|
NORMAL
|
2015-01-28T18:41:55+00:00
|
2015-01-28T18:41:55+00:00
| 3,808 | false |
The basic idea is to split the list in half, then reverse the second half, and at last merge them. It is O(n) time, O(1) space. I was also wondering if there is a better solution.\n\n class Solution {\n public:\n void reorderList(ListNode *head) {\n // use fast/slow points to find the second half of the list \n ListNode *head1, *head2;\n ListNode *preNode, *curNode;\n \n if(!head || !(head->next) )\n {// if the list is empty or only has one element\n return;\n }\n else\n {\n head1 = head;\n head2 = head->next;\n \n // find the starting point of the second half\n while(head2 && head2->next)\n {\n head1 = head1->next;\n head2 = (head2->next)->next;\n }\n \n //reverse the second half\n head2 =head1->next; // the head of the second half\n head1->next =NULL;\n preNode = NULL;\n \n while(head2)\n {\n curNode = head2->next;\n head2->next = preNode;\n preNode= head2;\n head2 = curNode;\n }\n \n // merge the first half and the reversed second half\n head2 = preNode;\n head1 = head;\n \n while(head2)\n {\n curNode = head1->next;\n head1 = head1->next = head2;\n head2 = curNode;\n }\n \n return;\n }\n }
| 16 | 0 |
[]
| 3 |
reorder-list
|
✅Super Easy Fast & Slow Pointer (C++/Java/Python) Solution With Detailed Explanation✅
|
super-easy-fast-slow-pointer-cjavapython-r00n
|
Intuition\nThe intuition is to first find the middle of the list using the slow and fast pointers method. Next, reverse the second half of the list starting fro
|
suyogshete04
|
NORMAL
|
2024-03-23T03:45:17.945215+00:00
|
2024-03-23T03:45:17.945251+00:00
| 4,946 | false |
# Intuition\nThe intuition is to first find the middle of the list using the slow and fast pointers method. Next, reverse the second half of the list starting from the middle. Finally, merge the two halves by alternately linking nodes from each half. This process rearranges the list in place, requiring only a fixed number of pointers for manipulation.\n\n# Approach\n\n1. **Find the Middle of the List**: The algorithm starts by finding the middle of the linked list using the slow and fast pointer technique. This is done by advancing one pointer (`slow`) by one node and another pointer (`fast`) by two nodes in each step. When `fast` reaches the end of the list, `slow` will be at the middle. This step ensures that the list can be divided into two halves for the subsequent steps.\n\n2. **Reverse the Second Half of the List**: Once the middle of the list is found, the next step is to reverse the second half of the list starting from the `slow` pointer. This is achieved by rearranging the pointers of the nodes in the second half such that their order is reversed.\n\n3. **Merge the Two Halves**: Finally, the first half and the reversed second half are merged together to form the reordered list. This merging is done by alternating nodes from the first and the second half until the reordering criteria are met.\n\n## Complexity Analysis\n\n1. **Time Complexity**:\n - **Finding the middle of the list**: This operation is \\(O(n)\\), where \\(n\\) is the number of nodes in the list, as it requires traversing half of the list.\n - **Reversing the second half of the list**: This operation is also \\(O(n)\\), but since it\'s only reversing the second half, it can be considered \\(O(n/2)\\). However, for big O notation, we drop constants, so it remains \\(O(n)\\).\n - **Merging the two halves**: The merge operation is \\(O(n)\\) because it involves traversing the entire list once to reorder the nodes.\n - **Total Time Complexity**: The overall time complexity is \\(O(n) + O(n) + O(n) = O(n)\\), which simplifies to \\(O(n)\\) since all steps are sequential.\n\n2. **Space Complexity**:\n - The algorithm modifies the list in place and uses a fixed number of pointer variables (`slow`, `fast`, `prev`, `next`, `firstHalf`, `secondHalf`). Thus, the space complexity is \\(O(1)\\), indicating that it requires a constant amount of additional space regardless of the input size.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n if (head == nullptr || head->next == nullptr) return;\n\n // Step 1: Find the middle of the list\n ListNode* slow = head;\n ListNode* fast = head;\n while (fast != nullptr && fast->next != nullptr) {\n slow = slow->next;\n fast = fast->next->next;\n }\n\n // Step 2: Reverse the second half of the list\n ListNode* prev = nullptr;\n ListNode* next = nullptr;\n while (slow != nullptr) {\n next = slow->next;\n slow->next = prev;\n prev = slow;\n slow = next;\n }\n\n // Step 3: Merge the two halves\n ListNode* firstHalf = head;\n ListNode* secondHalf = prev; // prev now points to the head of the reversed second half\n while (secondHalf->next) {\n next = firstHalf->next;\n prev = secondHalf->next;\n\n firstHalf->next = secondHalf;\n secondHalf->next = next;\n \n firstHalf = next;\n secondHalf = prev;\n }\n }\n};\n\n```\n```Java []\n\npublic class Solution {\n public void reorderList(ListNode head) {\n if (head == null || head.next == null) return;\n\n // Step 1: Find the middle of the list\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n\n // Step 2: Reverse the second half of the list\n ListNode prev = null, next = null;\n while (slow != null) {\n next = slow.next;\n slow.next = prev;\n prev = slow;\n slow = next;\n }\n\n // Step 3: Merge the two halves\n ListNode firstHalf = head;\n ListNode secondHalf = prev; // prev now points to the head of the reversed second half\n while (secondHalf.next != null) {\n next = firstHalf.next;\n prev = secondHalf.next;\n \n firstHalf.next = secondHalf;\n secondHalf.next = next;\n \n firstHalf = next;\n secondHalf = prev;\n }\n }\n}\n\n```\n```Python []\n\nclass Solution:\n def reorderList(self, head):\n if not head or not head.next:\n return\n\n # Step 1: Find the middle of the list\n slow, fast = head, head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n\n # Step 2: Reverse the second half of the list\n prev, curr = None, slow\n while curr:\n next_temp = curr.next\n curr.next = prev\n prev = curr\n curr = next_temp\n\n # Step 3: Merge the two halves\n first, second = head, prev\n while second.next:\n # Save next pointers\n tmp1 = first.next\n tmp2 = second.next\n \n # Reorder nodes\n first.next = second\n second.next = tmp1\n \n # Move pointers forward\n first = tmp1\n second = tmp2\n\n```
| 14 | 0 |
['Linked List', 'Two Pointers', 'C++', 'Java', 'Python3']
| 3 |
reorder-list
|
37.1 (Approach 1 : recursive) | O(n)✅ | Python & C++(Step by step explanation)✅
|
371-approach-1-recursive-on-python-cstep-fs5l
|
Intuition\nThe goal is to reorder a singly-linked list such that it is in the following pattern:\n\n1. 1st node -> nth node -> 2nd node -> (n-1)th node -> 3rd n
|
monster0Freason
|
NORMAL
|
2024-02-01T17:07:41.301878+00:00
|
2024-02-01T17:07:41.301903+00:00
| 1,532 | false |
## Intuition\nThe goal is to reorder a singly-linked list such that it is in the following pattern:\n\n1. 1st node -> nth node -> 2nd node -> (n-1)th node -> 3rd node -> (n-2)th node -> ...\n\n## Approach\n1. **Finding the Middle**: Use the "tortoise and hare" approach to find the middle of the linked list. Move `slow` one step and `fast` two steps. When `fast` reaches the end, `slow` will be at the middle.\n[141. Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/solutions/4661066/361-approach-1-recursive-on-python-cstep-by-step-explanation/)\n\n2. **Divide the List**: Set `h2` as the start of the second half (`slow.next`). Break the link between the first and second halves by setting `slow.next` to `None`.\n\n\n3. **Reverse the Second Half**: Reverse the second half of the linked list. Iterate through the second half and reverse the direction of the next pointers.\n[206. Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/solutions/4660673/342-approach-2-recursive-on-python-cstep-by-step-explanation/)\n\n4. **Merge Two Halves**: Merge the reversed second half with the first half. Alternate nodes from each half until both halves are merged.\n[21. Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/solutions/4660940/351-approach-1-recursive-on-python-cstep-by-step-explanation/)\n\n## Complexity\n- Time complexity: O(n), where n is the number of nodes in the linked list.\n- Space complexity: O(1) as we are reordering the list in-place.\n\n# Code(Python)\n```python\nclass Solution:\n def reorderList(self, head: ListNode) -> None:\n # Finding the middle of the linked list\n slow, fast = head, head.next\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n\n # Divide the linked list into two halves\n h2 = slow.next\n tail = slow.next = None\n\n # Reverse the second half of the linked list\n while h2:\n temp = h2.next\n h2.next = tail\n tail = h2\n h2 = temp\n\n # Merge two halves of the linked list\n h1, h2 = head, tail\n while h2:\n temp1, temp2 = h1.next, h2.next\n h1.next = h2\n h2.next = temp1\n h1, h2 = temp1, temp2\n```\n\n# Code(C++)\n```c++\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n // Finding the middle of the linked list\n ListNode* slow = head;\n ListNode* fast = head->next;\n while (fast && fast->next) {\n slow = slow->next;\n fast = fast->next->next;\n }\n\n // Divide the linked list into two halves\n ListNode* h2 = slow->next;\n slow->next = NULL;\n ListNode* tail = NULL;\n\n // Reverse the second half of the linked list\n while (h2) {\n ListNode* temp = h2->next;\n h2->next = tail;\n tail = h2;\n h2 = temp;\n }\n\n // Merge two halves of the linked list\n ListNode* h1 = head;\n h2 = tail;\n while (h2) {\n ListNode* temp1 = h1->next;\n ListNode* temp2 = h2->next;\n h1->next = h2;\n h2->next = temp1;\n h1 = temp1;\n h2 = temp2;\n }\n }\n};\n```\n\n\n# Please upvote the solution if you understood it.\n\n
| 13 | 0 |
['Linked List', 'Two Pointers', 'C++', 'Python3']
| 4 |
reorder-list
|
Awesome Slow Fast Logic
|
awesome-slow-fast-logic-by-ganjinaveen-gpn6
|
\n\n# Fast And Slow Logic\n\nclass Solution:\n def reorderList(self, head: Optional[ListNode]) -> None:\n # divide the linked list\n slow,fast=
|
GANJINAVEEN
|
NORMAL
|
2023-03-09T14:00:18.616503+00:00
|
2023-04-29T19:28:11.108490+00:00
| 2,329 | false |
\n\n# Fast And Slow Logic\n```\nclass Solution:\n def reorderList(self, head: Optional[ListNode]) -> None:\n # divide the linked list\n slow,fast=head,head.next\n while fast and fast.next:\n slow=slow.next\n fast=fast.next.next\n second=slow.next\n # making Null of half linked list\n prev=slow.next=None\n # reverse the end linked list\n while second:\n nxt=second.next\n second.next=prev\n prev=second\n second=nxt\n # merging the divided linked list\n first,last=head,prev\n while last:\n nxt1,nxt2=first.next,last.next\n first.next=last\n last.next=nxt1\n first,last=nxt1,nxt2\n \n```\n# please upvote me it would encourage me alot\n
| 13 | 0 |
['Python3']
| 2 |
reorder-list
|
Python in place solution with comments (two pointers).
|
python-in-place-solution-with-comments-t-mepb
|
For linked list 1->2->3->4-5, the code first makes the list to be 1->2->3->4<-5 and 4->None, then make 3->None, for even number linked list: 1->2->3->4, make fi
|
oldcodingfarmer
|
NORMAL
|
2015-07-16T19:15:27+00:00
|
2015-07-16T19:15:27+00:00
| 3,101 | false |
For linked list 1->2->3->4-5, the code first makes the list to be 1->2->3->4<-5 and 4->None, then make 3->None, for even number linked list: 1->2->3->4, make first 1->2->3<-4 and 3->None, and lastly do not forget to make 2->None. \n \n def reorderList(self, head):\n if not head:\n return\n # ensure the first part has the same or one more node\n fast, slow = head.next, head\n while fast and fast.next:\n fast = fast.next.next\n slow = slow.next\n # reverse the second half\n p = slow.next\n slow.next = None\n node = None\n while p:\n nxt = p.next\n p.next = node\n node = p\n p = nxt\n # combine head part and node part\n p = head\n while node:\n tmp = node.next\n node.next = p.next\n p.next = node\n p = p.next.next #p = node.next\n node = tmp
| 12 | 0 |
['Two Pointers', 'Python']
| 3 |
reorder-list
|
Clear C Solution
|
clear-c-solution-by-upthehell-867i
|
\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * struct ListNode *next;\n * };\n */\n \nstruct ListNode* getMid(struc
|
upthehell
|
NORMAL
|
2017-03-26T19:56:11.225000+00:00
|
2018-09-24T02:13:24.636436+00:00
| 1,018 | false |
```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * struct ListNode *next;\n * };\n */\n \nstruct ListNode* getMid(struct ListNode*);\nstruct ListNode* reverseList(struct ListNode*);\nvoid merge(struct ListNode*, struct ListNode*);\n\nvoid reorderList(struct ListNode* head) {\n if(head == NULL || head->next == NULL || head->next->next == NULL) return;\n \n struct ListNode* mid = getMid(head);\n struct ListNode* secondHalf = mid->next;\n mid->next = NULL;\n secondHalf = reverseList(secondHalf);\n merge(head, secondHalf);\n \n}\n\nstruct ListNode* getMid(struct ListNode* head){\n struct ListNode* fast = head;\n struct ListNode* slow = head;\n while(fast->next!=NULL && fast->next->next!=NULL){\n fast = fast->next->next;\n slow = slow->next;\n }\n return slow;\n}\n\nstruct ListNode* reverseList(struct ListNode* head) {\n struct ListNode* tail = NULL;\n while(head!=NULL){\n struct ListNode* cur = head;\n head = head->next;\n \n cur->next = tail;\n tail = cur;\n }\n \n return tail;\n}\n\nvoid merge(struct ListNode* head1, struct ListNode* head2){\n struct ListNode* head = head1;\n \n while(head2!=NULL){\n struct ListNode* next = head2->next;\n head2->next = head->next;\n head->next = head2;\n \n head = head->next->next;\n head2 = next;\n }\n}\n```
| 12 | 0 |
[]
| 0 |
reorder-list
|
My c++ solution for \u3010Reorder List\u3011AC within 72ms
|
my-c-solution-for-u3010reorder-listu3011-ehw8
|
class Solution {\n public:\n void reorderList(ListNode *head) {\n \t\tif (!head) return;\n \t\tListNode dummy(-1);\n \t\tdummy.next = head;\n
|
xiabofei
|
NORMAL
|
2015-05-01T01:27:05+00:00
|
2015-05-01T01:27:05+00:00
| 2,347 | false |
class Solution {\n public:\n void reorderList(ListNode *head) {\n \t\tif (!head) return;\n \t\tListNode dummy(-1);\n \t\tdummy.next = head;\n \t\tListNode *p1 = &dummy, *p2 = &dummy;\n \t\tfor (; p2 && p2->next; p1 = p1->next, p2 = p2->next->next);\n \t\tfor ( ListNode *prev = p1, *curr = p1->next; curr && curr->next; ){\n \t\t\tListNode *tmp = curr->next;\n \t\t\tcurr->next = curr->next->next;\n \t\t\ttmp->next = prev->next;\n \t\t\tprev->next = tmp;\n \t\t}\n \t\tfor ( p2 = p1->next, p1->next = NULL,p1 = head; p2; ){\n \t\t\tListNode *tmp = p1->next;\n \t\t\tp1->next = p2;\n \t\t\tp2 = p2->next;\n \t\t\tp1->next->next = tmp;\n \t\t\tp1 = tmp;\n \t\t}\n }\n };\n\n\n\nStep1. get the mid Node of the list\n\nStep2. reverse the second half list \n\nStep3. merge the two half lists\n\n**Clean & Concise is better**
| 12 | 0 |
['Linked List', 'C++']
| 4 |
reorder-list
|
Explained With Images. 1ms Solution. Beats 99%.
|
explained-with-images-1ms-solution-beats-qfbk
|
Approach\n\nThis Problem can be divided into three sub parts \n\n 1. https://leetcode.com/problems/middle-of-the-linked-list/description/\n 2. https://leetcode.
|
Kunal_Tajne
|
NORMAL
|
2024-08-11T14:33:52.281511+00:00
|
2024-08-11T14:37:14.386796+00:00
| 1,139 | false |
# Approach\n\nThis Problem can be divided into three sub parts \n\n 1. https://leetcode.com/problems/middle-of-the-linked-list/description/\n 2. https://leetcode.com/problems/reverse-linked-list/description/\n 3. Merge two lists, which we will discover in this problem.\n\nWe need to perform the in-place reversal for the second half of the linked list, which will allow us to not use any extra memory. To solve the original problem, we can use the modified in-place methodology after the first in-place reversal to merge the two halves of the linked list. We can use two-pointers, first and second, to point to the heads of the two halves of the linked list. We\u2019ll traverse both halves in lockstep to merge the two linked lists, interleaving the nodes from the second half into the first half.\n\n## Below are the illustrations to help you understand better :\n\n\n\n\n\n\n\n\n# Complexity\n- Time complexity:\nThe time complexity of this solution is linear, $$O(n)$$\n\n- Space complexity:\nThe space complexity of the solution is constant, $$O(1)$$\n\n# Code\n```\nclass Solution {\n public void reorderList(ListNode head) {\n \n \tif(head == null)\n\t\t return head;\n\t\t// find the middle of linked list\n\t\t// in 1->2->3->4->5->6 find 4 \n\t\tLinkedListNode slow = head; \n\t\tLinkedListNode fast = head;\n\n\t\twhile(fast!= null && fast.next != null)\n\t\t{\n\t\t\tslow = slow.next;\n\t\t\tfast = fast.next.next;\n\t\t}\n\t\t// reverse the second part of the list\n // convert 1->2->3->4->5->6 into 1->2->3 and 6->5->4\n // reverse the second half in-place\n\t\tLinkedListNode prev = null;\n\t\tLinkedListNode curr = slow;\n\t\tLinkedListNode next = null;\n\n\t\twhile(curr != null)\n\t\t{\n\t\t\tnext = curr.next;\n\t\t\tcurr.next = prev;\n\t\t\tprev = curr;\n\t\t\tcurr = next;\n\t\t}\n\t\t// merge two sorted linked lists\n // merge 1->2->3 and 6->5->4 into 1->6->2->5->3->4\n\t\tLinkedListNode first = head;\n\t\tLinkedListNode second = prev;\n\t\tLinkedListNode temp = head;\n\n while(second.next != null)\n\t\t{\n\t\t\ttemp = temp.next;\n\t\t\tfirst.next = second;\n\t\t\tsecond = second.next;\n\t\t\tfirst.next.next = temp;\n\t\t\tfirst = first.next.next;\n\t\t}\n\n\t\treturn head;\n}\n}\n```\n\n\n
| 11 | 0 |
['Linked List', 'Two Pointers', 'C++', 'Java', 'Python3']
| 0 |
reorder-list
|
O(N) Time complexity Two pointer approach
|
on-time-complexity-two-pointer-approach-uqktq
|
Intuition\n Describe your first thoughts on how to solve this problem. \nStore all elements of the linked list and then by two pointers make the required linked
|
Harshsharma6371
|
NORMAL
|
2024-03-23T16:20:57.844749+00:00
|
2024-03-23T16:20:57.844776+00:00
| 488 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nStore all elements of the linked list and then by two pointers make the required linked list.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMake a list to store all the nodes taking O(n) space complexity. Make two pointers from 1th index and length(list)-1 index. Add the last pointer to the head and then add the element of first index to it. Repeat it till low>high. Then clear the address of the last node and the question is done.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def reorderList(self, head: Optional[ListNode]) -> None:\n """\n Do not return anything, modify head in-place instead.\n """\n lst=[]\n start=head\n while(start!=None):\n lst.append(start)\n start=start.next\n length=len(lst)\n low=1\n high=length-1\n start=head\n while(low<=high):\n \n start.next=lst[high]\n high-=1\n start=start.next\n start.next=lst[low]\n start=start.next\n low+=1\n start.next=None\n\n\n```
| 11 | 0 |
['Python3']
| 1 |
reorder-list
|
Video solution | Intuition and Approach Explained in detail | C++ | Recursion
|
video-solution-intuition-and-approach-ex-0grc
|
Video solution \n Describe your first thoughts on how to solve this problem. \n\nhey everyone, i have made video playlist for Recursion where i explain intuitio
|
_code_concepts_
|
NORMAL
|
2024-03-14T16:15:17.326176+00:00
|
2024-03-14T16:16:41.761938+00:00
| 541 | false |
# Video solution \n<!-- Describe your first thoughts on how to solve this problem. -->\n\nhey everyone, i have made video playlist for Recursion where i explain intuition behind it, this video solution is part of my playlist.\nLink for video:\nhttps://youtu.be/bCiIQSZSTUc\n\n\nLink for playlist: https://www.youtube.com/playlist?list=PLICVjZ3X1AcbI-9LyJ6ss-gB3bNRTQrll\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n\n // L1->L2->L3->......Ln/2->.....Ln-2->Ln-1->Ln\n // L1->Ln->L2->L3->L4......->Ln-1->null\n \n void reorderList(ListNode* head) {\n //BC\n if(head==NULL || head->next==NULL || head->next->next==NULL){\n return;\n \n \n }\n\n //task\n ListNode* second_last= head;\n while(second_last->next->next){\n second_last=second_last->next;\n }\n second_last->next->next=head->next;\n head->next=second_last->next;\n second_last->next=NULL;\n\n //rr\n reorderList(head->next->next);\n \n\n }\n};\n```
| 11 | 0 |
['C++']
| 2 |
reorder-list
|
[Java] Merging + Two Pointers solution with clear explanation and real life application. 🔥
|
java-merging-two-pointers-solution-with-1wclx
|
Intuition\nThe problem "Reorder List" asks us to reorder a singly linked list such that it has a specific structures: the first node, followed by the last node,
|
anhle_tr
|
NORMAL
|
2023-04-05T21:42:49.602729+00:00
|
2023-04-05T21:42:49.602768+00:00
| 893 | false |
# Intuition\nThe problem "Reorder List" asks us to reorder a singly linked list such that it has a specific structures: the first node, followed by the last node, then the second node, then the second-to-last node, and so on. \n\nThis problem is a combination and modification of these 3 problems: Middle of the Linked List, Reversed Linked List, Merge Sort. Here are the links to each:\n\n1. https://leetcode.com/problems/middle-of-the-linked-list/\n2. https://leetcode.com/problems/reverse-linked-list/\n3. https://leetcode.com/problems/merge-sorted-array/\n\n\nHere is the intuition behind this approach.\n\n1. Divide the linked list into two halves by finding the middle node using the slow-fast pointer technique.\n\n2. Reverse the second half of the list.\n\n3. Merge the two halves into a single sorted linked list.\n\n\n# Approach\nHere is the approach to this problem:\n\n1. Split the original list into two halves: We can split the list into two halves using the slow-fast pointer technique. This will give us two separate lists: the first half starts at the head of the original list and ends before the middle node, and the second half starts at the middle node and ends at the tail.\n\n2. Reverse the second half of the list: We need to reverse the second half of the list because we want to start with the last node and work our way towards the middle. \n\n3. Merge the two halves: After we have the two separate lists, we can merge them in the required order. We can do this by starting with the first node of the first list and the last node of the second list, then alternating between nodes from both lists until we reach the middle of the list.\n\n\n\n# Code\n```\nclass Solution {\n public void reorderList(ListNode head) {\n //find middle element\n ListNode slow = head;\n ListNode fast = head.next;\n while(fast != null && fast.next != null)\n {\n slow = slow.next;\n fast = fast.next.next;\n }\n\n //reverse the second half of the list starting from the middle\n ListNode prev = null;\n while(slow != null)\n {\n ListNode temp = slow.next;\n slow.next = prev;\n prev = slow;\n slow = temp;\n }\n\n //Merge two halves\n ListNode p1 = head;\n ListNode p2 = prev;\n while (p1 != null) {\n ListNode next1 = p1.next;\n ListNode next2 = p2.next;\n p1.next = p2;\n p2.next = next1;\n p1 = next1;\n p2 = next2;\n }\n }\n}\n```\n\n# Complexity\n- Time complexity: $$O(n)$$ where n is the length of the linked list. This is because we only need to traverse the list twice to find the middle node and reverse the second half of the list, and then traverse the list again to merge the two halves.\n\n- Space complexity: $$O(1)$$ because we only use a constant amount of extra space.\n\n# Application\nThe Reorder List problem have several real-life applications:\n\n1. **Browser Hsitory**: a browser history is typically implement using a linked list data structure, where each webpage visited is stored as a node in the list.\n\n2. **Music Playlists**: each song is stored as a node in the list, and the order of songs in the playlist is determined by the order of nodes in the list.\n\n3. **File systems:** a file system is usually organized as a hierarchy of directories and files. Each directory and file can be represented as a node in a linked list, with a pointer to its parent directory and a list of child nodes.\n\n4. **LRU Cache:** a LRU (Least Recently Used) cache is common caching stategy used in computer systems to store recently accessed items.\n\n5. **Garbage collection**: implmented using a linked list of objects that are no longer in use called "free list". The garbage colletor scans this list periodically to free up memory.\n\n\n5. **Image manipulation**: represent images as a set of pixels. Each pixel is stored as a node in the list, with a pointer to its neighboring pixels.\nThis allow for efficient image manipulation, such as scaling or cropping.\n\n*Thank you for reading! If you found this solution helpful, please give me an upvote. Feel free to add suggestions.*\n
| 11 | 0 |
['Linked List', 'Two Pointers', 'Java']
| 1 |
reorder-list
|
JavaScript solution with 3 steps
|
javascript-solution-with-3-steps-by-haoy-t379
|
Steps:\n1. use fast & slow pointer to get to the middle of linked list. Note when list has even number of nodes, get the middle left node of the list.\n2. break
|
haoyangfan
|
NORMAL
|
2019-09-25T17:29:53.228740+00:00
|
2019-09-26T17:01:01.825268+00:00
| 775 | false |
##### Steps:\n1. use fast & slow pointer to get to the middle of linked list. Note when list has even number of nodes, get the middle left node of the list.\n2. break the list in the middle, and reverse the second half of the list \n3. interleave the reversed second half with the first half\n\nImplementation:\n```js\nvar reorderList = function(head) {\n // nothing need to be done in case list is either empty or contains only one or two nodes\n if (!head || !head.next || !head.next.next) return head;\n\n // step 1: use fast and slow pointer to move to the middle of linked list\n // in case list is even, then move to the middle left node\n let fast = head.next, slow = head;\n while (fast && fast.next) {\n fast = fast.next.next;\n slow = slow.next;\n }\n\n // get the second half of list\n const secondHalf = slow.next;\n\n // break the list\n slow.next = null;\n\n // step 2: reverse the second half\n let curr = secondHalf, prev = null, tmp;\n\n while (curr) {\n tmp = curr.next;\n curr.next = prev;\n prev = curr;\n curr = tmp;\n }\n\n // step 3: interleave the first half with second half\n let first = head, second = prev;\n while (second) {\n tmp = first.next;\n first.next = second;\n second = second.next;\n first.next.next = tmp;\n first = tmp;\n }\n};\n```\nHappy Coding~
| 11 | 0 |
[]
| 1 |
reorder-list
|
Very Very Very simple idea by using a stack
|
very-very-very-simple-idea-by-using-a-st-qugr
|
For example:\n1 2 3 4 5\nyou just create a stack like this:\n5 4 3 2 1\nthen link with 1->5->2->4->3\uFF0Cuse half nodes of the stack, finaly cut the last node
|
mcdull0921
|
NORMAL
|
2019-05-22T09:43:26.693195+00:00
|
2019-06-17T09:59:28.679582+00:00
| 1,830 | false |
For example:\n1 2 3 4 5\nyou just create a stack like this:\n5 4 3 2 1\nthen link with 1->5->2->4->3\uFF0Cuse half nodes of the stack, finaly cut the last node , set 3->None\n```\n if not head:\n return\n stack=[]\n node=head\n while node:\n stack.append(node)\n node=node.next\n node=head\n for i in range(len(stack)//2):\n n=stack.pop()\n t=node.next\n node.next=n\n n.next=t\n node=t\n node.next=None \n```
| 11 | 0 |
['Stack', 'Python3']
| 3 |
reorder-list
|
💥[EXPLAINED] TypeScript. Runtime beats 95.90%, Memory beats 27.44%
|
explained-typescript-runtime-beats-9590-mh3yd
|
Intuition\nThe goal is to reorder the linked list so that the nodes are arranged in an alternating pattern from the beginning and end towards the center. This i
|
r9n
|
NORMAL
|
2024-08-24T12:33:43.123033+00:00
|
2024-08-24T12:33:43.123118+00:00
| 157 | false |
# Intuition\nThe goal is to reorder the linked list so that the nodes are arranged in an alternating pattern from the beginning and end towards the center. This involves splitting the list, reversing the second half, and merging the two halves.\n\n# Approach\nFind the Middle: Use a fast and slow pointer to find the middle of the list.\n\nReverse the Second Half: Reverse the second half of the list starting from the middle.\n\nMerge the Halves: Merge the first half with the reversed second half to achieve the reordered list.\n\n# Complexity\n- Time complexity:\nO(n): Traversing the list, reversing the second half, and merging the halves all take linear time.\n\n- Space complexity:\nO(1): The reordering is done in place, using only a constant amount of extra space.\n\n# Code\n```typescript []\nfunction reorderList(head: ListNode | null): void {\n if (!head || !head.next || !head.next.next) return;\n\n // Step 1: Find the middle of the linked list\n let slow = head;\n let fast = head;\n while (fast && fast.next) {\n slow = slow!.next!;\n fast = fast.next.next;\n }\n\n // Step 2: Reverse the second half of the list\n let second = slow.next;\n slow.next = null; // Split the list into two halves\n let prev: ListNode | null = null;\n while (second) {\n const next = second.next;\n second.next = prev;\n prev = second;\n second = next;\n }\n let reversedSecond = prev;\n\n // Step 3: Merge the two halves\n let first = head;\n while (reversedSecond) {\n const tmp1 = first.next;\n const tmp2 = reversedSecond.next;\n\n first.next = reversedSecond;\n reversedSecond.next = tmp1;\n\n first = tmp1;\n reversedSecond = tmp2;\n }\n}\n\n```
| 10 | 0 |
['TypeScript']
| 1 |
reorder-list
|
Easy Beginner Friendly 🔥💯❤ || O(n) 🚀|| C++ ✔
|
easy-beginner-friendly-on-c-by-devilback-tz4u
|
Intuition & Approach:\n\nso here, after seeing all solution and problems everyone is facing, i just brough a simplest approach for this problem with easy way to
|
DEvilBackInGame
|
NORMAL
|
2024-03-23T03:35:52.687126+00:00
|
2024-03-23T03:35:52.687159+00:00
| 2,752 | false |
# Intuition & Approach:\n\nso here, after seeing all solution and problems everyone is facing, i just brough a simplest approach for this problem with easy way to arrange all nodes in orderwise given A.T.Q.\n\n***Lets see these steps:***\n1. **Save Addresses**: Traverse the linked list and save the addresses of all nodes in a vector `arr`.\n\n2. **Set Pointers**: After saving all addresses, initialize two pointers `i` and `j` to the `beginning` and `end` of the vector respectively. Also, initialize a pointer `t1` to the first element of the vector.\n\n3. **Rearrange Nodes**: In a loop, rearrange the pointers to `reorder` the list. The basic idea is to take the node pointed by `j` and set it as the `next node` of the node pointed by `i`, then move `j `backward. Next, take the node pointed by` i` and set it as the next node of the node pointed by `j`, then move `i` forward. Repeat this process until `i` becomes `greater than or equal` to `j`.\n\n4. **Terminate the List**: After the loop, ensure proper termination of the reordered list by setting the next pointer of the last node to `nullptr`.\n\nThis approach ensures that we are properly rearranging the pointers to reorder the list while traversing it just once.\n\n\n\n\n***for better undestanding see code below:-***\n# Code:\n***T.C -> O(n)***\n```C++ []\n\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n if (!head || !head->next)\n return; // No need to reorder for empty or single node list\n\n vector<ListNode*> arr; // to save address of all list nodes\n ListNode* temp = head;\n\n while (temp != nullptr) {\n arr.push_back(temp);\n temp = temp->next;\n }\n\n int i = 0, j = arr.size() - 1;\n while (i < j) {\n arr[i]->next = arr[j];\n i++;\n\n if (i == j) break; // Break if i and j meet\n\n arr[j]->next = arr[i];\n j--;\n }\n arr[i]->next = nullptr;\n }\n};\n\n```
| 10 | 1 |
['Array', 'Linked List', 'Two Pointers', 'C++']
| 5 |
reorder-list
|
🔥🔥🔥🔥🔥 Beat 99% 🔥🔥🔥🔥🔥 EASY 🔥🔥🔥🔥🔥🔥
|
beat-99-easy-by-abdallaellaithy-fyph
|
\n\n\n# Code\n\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n#
|
abdallaellaithy
|
NORMAL
|
2024-03-23T00:02:39.084976+00:00
|
2024-03-23T01:52:49.999651+00:00
| 5,289 | false |
[](https://leetcode.com/problems/reorder-list/submissions/1211291357/)\n\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n # Function for reversing\n def reverse(self, head):\n prev = None\n current = head\n while current:\n prev, prev.next, current = current, prev, current.next\n return prev\n \n def reorderList(self, head):\n """\n :type head: ListNode\n :rtype: None Do not return anything, modify head in-place instead.\n """\n if head is None:\n return\n\n fast = head.next\n slow = head\n # Catch the Middle of List (slow)\n while fast and fast.next:\n fast = fast.next.next\n slow = slow.next\n # Cut Middle of list then Reverse it\n rev = self.reverse(slow.next)\n slow.next = None\n\n while rev:\n h_next = head.next\n r_next = rev.next\n head.next = rev\n rev.next = h_next\n rev = r_next\n head = h_next \n```
| 10 | 1 |
['Python', 'Python3']
| 6 |
reorder-list
|
[Go] Solution
|
go-solution-by-harotobira-ehha
|
Runtime: 8 ms, faster than 92.81% of Go online submissions for Reorder List.\nMemory Usage: 5.4 MB, less than 50.00% of Go online submissions for Reorder List.\
|
harotobira
|
NORMAL
|
2020-04-13T18:23:31.001864+00:00
|
2020-04-13T18:23:31.001916+00:00
| 658 | false |
Runtime: 8 ms, faster than 92.81% of Go online submissions for Reorder List.\nMemory Usage: 5.4 MB, less than 50.00% of Go online submissions for Reorder List.\n```\n/**\n * Definition for singly-linked list.\n * type ListNode struct {\n * Val int\n * Next *ListNode\n * }\n */\nfunc reorderList(head *ListNode) {\n if head == nil || head.Next == nil {\n return\n }\n \n slow, fast := head, head\n for fast != nil && fast.Next != nil {\n slow, fast = slow.Next, fast.Next.Next\n }\n \n var prev *ListNode\n for slow != nil {\n slow.Next, prev, slow = prev, slow, slow.Next\n }\n \n\n first := head\n for prev.Next != nil{\n first.Next, first = prev, first.Next\n prev.Next, prev = first, prev.Next\n }\n}\n```
| 10 | 0 |
['Go']
| 2 |
reorder-list
|
Concise recursive O(N) solution with O(1) space, easy to understand
|
concise-recursive-on-solution-with-o1-sp-h2t5
|
class Solution {\n public:\n void reorderList(ListNode* head) {\n ListNode* temp = head;\n helper(temp, head);\n }\n \n
|
laskuma
|
NORMAL
|
2016-03-20T18:22:29+00:00
|
2016-03-20T18:22:29+00:00
| 1,676 | false |
class Solution {\n public:\n void reorderList(ListNode* head) {\n ListNode* temp = head;\n helper(temp, head);\n }\n \n private:\n bool helper(ListNode*& head, ListNode* node) {\n if (!node) { // Find the last node\n return false;\n }\n if (helper(head, node->next)) { // Stop recursion if mid point has met\n return true;\n }\n if (node == head || node == head->next) { // Change newEnd->next to NULL and tell the function to stop\n node->next = NULL;\n return true;\n }\n ListNode *temp = head;\n head = head->next;\n temp->next = node;\n node->next = head;\n \n return false; // Ask the function to continue\n }\n };\n\nThe idea is quite simple here. First we use recursion to find the last node then start doing the reordering. The tricky part is how to tell the function to stop when the mid point has met. Here I simply modify this function to return a boolean value, the returned value is whether this function should stop.\n\nHope this could help you a little bit. :)
| 10 | 2 |
[]
| 3 |
reorder-list
|
Reorder List - Easy Explaination Java
|
reorder-list-easy-explaination-java-by-a-r3m2
|
Problem Statement Explained\n\nThis question asks us to reorder a linked list in this way : L0 \u2192 Ln \u2192 L1 \u2192 Ln-1 \u2192 L2 \u2192 Ln-2 \u2192 \u20
|
ak9807
|
NORMAL
|
2024-07-15T18:44:01.746053+00:00
|
2024-07-15T18:44:01.746076+00:00
| 599 | false |
# Problem Statement Explained\n\nThis question asks us to reorder a linked list in this way : L0 \u2192 Ln \u2192 L1 \u2192 Ln-1 \u2192 L2 \u2192 Ln-2 \u2192 \u2026 \n\nWe are going to use a stack for this problem because of the LIFO property of stack which will allow us to access the last element of the list.\n \n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIn this question , we have to reorder a linked list . \nso , if a linked list is **1-2-3-4-5** , after re ordering , it will become **1-5-2-4-3** .\nWhat we\'ll do now is , push all the nodes of the linked list into the stack.\nAnd to add do that , we first assign head\'s address to a local node temp. `ListNode temp = head` \n> This should be our first step in almost every linked list question because head doesn\'t move , hence we always assign it\'s address to a temporary pointer.\n\nAfter , pushing all nodes into the stack , we iterate for n/2 times and do the re-ordering of the list . \n\n**Why n/2 ?**\n\n> Each iteration processes two nodes: one from the start and one from the end of the list.\nIn a list of size \uD835\uDC5B, we need to do this pairing n/2 times to cover all nodes.\nFor a list of size 5:\nIteration 1: handles nodes 1 and 5.\nIteration 2: handles nodes 2 and 4.\n---\n# Code Walkthrough\n\nWhen we are iterating for n/2 times , we do the following assignments :\n```\nListNode next=temp.next;\nListNode last = stack.pop();\ntemp.next=last;\nlast.next=next;\ntemp=next;\n\n```\nLet\'s take an example of a Linked List `1-2-3-4-5`. After we push these elements inside the stack , our stack now contains : `5-4-3-2-1`\n(with `5` being on top of the stack , since it was the last processed in the list).\n\n1. In **`For i=0`** : we assign `next` node with the next of `temp`.\nas in line of code `ListNode next=temp.next;` so now, `temp = 1` . \nthen `last node` is initialized with stack.pop() which means that `last = 5`. \n\nSo now , we link these nodes together in the order we want .\n`\n temp.next=last;\n last.next=next;\n temp=next;`\nthis gives us 1-5-2-3-4 ,the stack contains [4,3,2,1] and the temp points to 2 now\n\n2. **`For i=1`** : next =3 , last = 4 and after linking the nodes , we get 1-5-2-4-3 and temp =3.\n\n3. **`For i=2`** : (n/2 iterations are completed ) temp = 3 and 3 points to null now , which means list has terminated.\n\n\n---\n# Complexity\n- Time complexity : $$O(n)$$\n<!-- Add your time complexity here, e.g. -->\n\n- Space complexity : $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n---\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public void reorderList(ListNode head) {\n Stack<ListNode>stack = new Stack<>();\n if(head==null || head.next==null)\n {\n return;\n }\n\n ListNode temp=head;\n\n while(temp!=null)\n {\n stack.push(temp);\n temp=temp.next;\n }\n \n int n = stack.size();\n temp=head;\n\n for(int i=0;i<n/2;i++)\n {\n ListNode next=temp.next;\n ListNode last = stack.pop();\n\n temp.next=last;\n last.next=next;\n temp=next;\n \n\n }\n\n temp.next=null;\n }\n}\n```\n---\n**Feel free to discuss this problem in the comments section and also , do upvote if you liked the explaination ThankYou !**
| 9 | 0 |
['Linked List', 'Two Pointers', 'Stack', 'Java']
| 0 |
reorder-list
|
YOU WILL NEVER FORGET THIS SOLUTION🤯 || JAVA 100% FASTER🔥🔥|| STEP BYSTEP EXPLAINED😊
|
you-will-never-forget-this-solution-java-jtnz
|
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
|
abhiyadav05
|
NORMAL
|
2023-03-18T05:34:23.522950+00:00
|
2023-03-18T05:36:18.909095+00:00
| 1,248 | false |
# 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)$$ -->O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(1)\n\n\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public void reorderList(ListNode head) {\n // Check if the given list is empty or has only one element\n if (head == null || head.next == null) {\n return;\n }\n \n // Find the middle node of the list\n ListNode slow = head;\n ListNode fast = head;\n while (fast.next != null && fast.next.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n \n // Reverse the second half of the list\n ListNode prev = null;\n ListNode curr = slow.next;\n slow.next = null;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n \n // Merge the two halves of the list\n ListNode p1 = head;\n ListNode p2 = prev;\n while (p2 != null) {\n ListNode next1 = p1.next;\n ListNode next2 = p2.next;\n p1.next = p2;\n p2.next = next1;\n p1 = next1;\n p2 = next2;\n }\n }\n}\n```
| 9 | 0 |
['Linked List', 'Java']
| 1 |
reorder-list
|
C++ || Stack || easy-understanding
|
c-stack-easy-understanding-by-drishti121-uwuv
|
Its really easy to understand , we first use tortoise-hare method to reach at the mid and end element then push last half linked list into stack and then insert
|
drishti1210
|
NORMAL
|
2022-05-16T14:28:04.550094+00:00
|
2022-05-16T14:28:04.550140+00:00
| 979 | false |
Its really easy to understand , we first use **tortoise-hare** method to reach at the mid and end element then push last half linked list into stack and then insert its top element in between the the first half linked list.\n```\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n if(head == NULL || head->next == NULL || head->next->next == NULL) return ;\n ListNode* slow= head;\n ListNode* fast= head;\n stack<ListNode*> st;\n while( fast!=NULL && fast->next!=NULL){\n slow= slow->next;\n fast = fast->next->next;\n }\n ListNode* n;\n \n if(fast!=NULL){\n n= slow->next;\n \n }\n else n= slow;\n \n while(n!=NULL){\n st.push(n);\n n= n->next;\n \n }\n fast= head;\n \n while(st.size()){\n \n n = fast->next; \n fast->next= st.top();\n st.top()->next =n;\n fast=n;\n st.pop();\n \n }\n slow->next= NULL;\n \n \n }\n};\n\n\n```
| 9 | 0 |
['Linked List', 'Stack', 'Recursion', 'C', 'C++']
| 2 |
reorder-list
|
[C++] Hare-based Solution Explained, ~100% Time, ~60% Space
|
c-hare-based-solution-explained-100-time-mh2c
|
This was a complex one for me, since I never reverted a listed string in-place and could not focus enough for a while to spot silly mistakes.\n\nAnyway, much mo
|
ajna
|
NORMAL
|
2020-08-20T22:15:09.203611+00:00
|
2020-08-21T19:56:28.052314+00:00
| 1,461 | false |
This was a complex one for me, since I never reverted a listed string in-place and could not focus enough for a while to spot silly mistakes.\n\nAnyway, much more efficiently than [my other attempt](https://leetcode.com/problems/reorder-list/discuss/801842/C%2B%2B-Simple-Recursive-vs.-Iterative-Approaches-Compared-and-Explained-~10-Time-~60-Space), this solution delivers good results and goes in linear time (the previous was quadratic), moving from ~1000ms down up to 28ms, with 40-50ms on average.\n\nThis solution can be divided in 3 steps:\n* finding the first half of the array with the hare approach (ie: having 2 iterators parse it, one moving at double speed and thus when it will be finished, the other has to be midway) and possibly adjusting it with lists of even length;\n* reverting the list from `half` up to the end - the part that gave me a non-indifferent pain, since I was dumb, period. More info on linked list reversal [here](https://leetcode.com/problems/reverse-linked-list/discuss/803955/);\n* merging the first half starting with `head` together with the reverted second part starting with `half`, this time having to close things in case we were dealing with an even-lengthed list.\n\nThe code:\n\n```cpp\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n // exiting for empty lists\n if (!head) return;\n // finding the central node with the hare approach\n ListNode *tmp = head, *half = head, *prev = NULL;\n while (tmp->next && tmp->next->next) {\n tmp = tmp->next->next;\n half = half->next;\n }\n // adding one bit in case of lists with even length\n if (tmp->next) half = half->next;\n // reversing the second half\n while (half) {\n tmp = half->next;\n half->next = prev;\n prev = half;\n half = tmp;\n }\n half = prev;\n // merging the 2 lists\n while (head && half) {\n tmp = head->next;\n prev = half->next;\n head->next = half;\n half->next = tmp;\n head = tmp;\n half = prev;\n }\n // closing when we had even length arrays\n if (head && head->next) head->next->next = NULL;\n }\n};\n```
| 9 | 0 |
['Linked List', 'C', 'C++']
| 6 |
reorder-list
|
My java solution in O(n) time
|
my-java-solution-in-on-time-by-fiona_mao-bo3y
|
//1. find the middle node\n //2. reverse the right side of the list\n //3. merger the left side list and right side list\n \n \n public c
|
fiona_mao
|
NORMAL
|
2014-10-04T01:31:53+00:00
|
2014-10-04T01:31:53+00:00
| 3,918 | false |
//1. find the middle node\n //2. reverse the right side of the list\n //3. merger the left side list and right side list\n \n \n public class Solution {\n public void reorderList(ListNode head) {\n if(head==null) return;\n ListNode slow = head, fast = head;\n while(fast!=null && fast.next!=null){\n slow = slow.next;\n fast = fast.next.next;\n }\n ListNode mid = slow, cur = slow.next;\n if(cur!=null){\n ListNode tmp = cur.next;\n cur.next = null;\n cur = tmp;\n }\n while(cur!=null){\n ListNode tmp = cur.next;\n cur.next = mid.next;\n mid.next = cur;\n cur = tmp;\n }\n ListNode left = head, right = mid.next;\n while(right!=null){\n mid.next = right.next;\n right.next = left.next;\n left.next = right;\n left = right.next;\n right = mid.next;\n }\n \n }\n }
| 9 | 0 |
[]
| 2 |
reorder-list
|
🔧 Efficient Linked List Reordering with Python: 99% Runtime Optimization
|
efficient-linked-list-reordering-with-py-b0w2
|
Intuition\n Describe your first thoughts on how to solve this problem. \nTo reorder a singly linked list such that it alternates between the start and end nodes
|
LinhNguyen310
|
NORMAL
|
2024-07-23T17:12:55.056480+00:00
|
2024-07-23T17:12:55.056512+00:00
| 353 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo reorder a singly linked list such that it alternates between the start and end nodes, you need to:\n\nFind the middle of the list.\nReverse the second half of the list.\nMerge the two halves by alternating nodes from each half.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFind the Middle: Use the slow and fast pointer technique to find the middle node of the list. The slow pointer moves one step at a time, while the fast pointer moves two steps at a time. When the fast pointer reaches the end, the slow pointer will be at the middle.\n\nReverse the Second Half: Starting from the node right after the middle node, reverse the second half of the list. This involves changing the next pointers of the nodes to point in the reverse direction.\n\nMerge the Two Halves: Alternate between nodes from the first half and nodes from the reversed second half. This is done by linking nodes from the two halves together in the correct order.\n# Complexity\nTime Complexity:\n\nFinding the middle node takes \nO(n) time, where \n\uD835\uDC5B\nn is the number of nodes in the list.\nReversing the second half also takes \nO(n/2) time, which simplifies to \nO(n).\nMerging the two halves takes \nO(n) time.\nOverall, the time complexity is \nO(n).\nSpace Complexity:\n\nThe algorithm only uses a constant amount of extra space, aside from the input list. Hence, the space complexity is \nO(1).\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n def reorderList(self, head):\n """\n :type head: ListNode\n :rtype: None Do not return anything, modify head in-place instead.\n """\n temp = head\n\n def findMiddle(temp):\n slow, fast = temp, temp\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n\n return slow\n \n def reverseList(node):\n prev, curr = None, node\n while curr:\n nextTemp = curr.next\n curr.next = prev\n prev = curr\n curr = nextTemp\n return prev\n \n def mergeList(startP, midP):\n while midP:\n # store the next node\n startNext = startP.next\n midNext = midP.next\n\n # link node to second\n startP.next = midP\n\n # link mid to next node\n midP.next = startNext\n\n # mvoe pointer to the next one\n startP = startNext\n midP = midNext\n\n middle = findMiddle(temp)\n second_half = reverseList(middle.next)\n middle.next = None # Split the list into two halves\n \n # Merge the two halves\n mergeList(head, second_half) \n```\n\n
| 8 | 0 |
['Linked List', 'Two Pointers', 'Python', 'Python3']
| 2 |
reorder-list
|
Best O(N) Solution
|
best-on-solution-by-kumar21ayush03-v4lt
|
Approach\nUsing Stack\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n\n/**\n * Definition for singly-linked list.\n * struct
|
kumar21ayush03
|
NORMAL
|
2023-09-23T07:53:35.168247+00:00
|
2023-09-23T07:53:35.168270+00:00
| 882 | false |
# Approach\nUsing Stack\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n int size = 0;\n ListNode* dummy = head;\n stack <ListNode*> nodes;\n while (dummy != NULL) {\n nodes.push(dummy);\n size++;\n dummy = dummy->next;\n }\n dummy = head;\n for (int i = 0; i < size / 2; i++) {\n ListNode* temp = dummy->next;\n dummy->next = nodes.top();\n nodes.pop();\n dummy = dummy->next;\n dummy->next = temp;\n dummy = temp;\n }\n dummy->next = NULL;\n }\n};\n```
| 8 | 0 |
['C++']
| 1 |
reorder-list
|
3 solutions - With stack, without stack and recursion solutions || Beats 100% !!
|
3-solutions-with-stack-without-stack-and-9yfv
|
Code\n\n// Solution 1 - Without stack\nclass Solution {\npublic:\n // Function to reverse the LL\n ListNode *reverse(ListNode *head){\n ListNode *c
|
prathams29
|
NORMAL
|
2023-08-09T13:15:14.542180+00:00
|
2023-08-09T13:15:57.107614+00:00
| 1,144 | false |
# Code\n```\n// Solution 1 - Without stack\nclass Solution {\npublic:\n // Function to reverse the LL\n ListNode *reverse(ListNode *head){\n ListNode *curr = head, *prev = NULL, *forward = NULL;\n while(curr != NULL){\n forward = curr->next;\n curr->next = prev;\n prev = curr;\n curr = forward;\n }\n return prev;\n }\n\n void reorderList(ListNode* head) {\n // Check for edge cases\n if(head->next == NULL || head->next->next == NULL)\n return;\n\n // Step 1 - Find middle of the LL with slow-fast pointer approach\n ListNode *slow = head, *fast = head, *slow_prev = NULL;\n while(fast != NULL && fast->next != NULL){\n slow_prev = slow;\n slow = slow->next;\n fast = fast->next->next;\n }\n\n // Step 2 - Split the LL into 2 parts from the middle \n // and reverse the second part\n ListNode *h1 = head, *h2;\n if(fast == NULL){\n h2 = reverse(slow);\n slow_prev->next = NULL;\n }\n else{\n h2 = reverse(slow->next);\n slow->next = NULL;\n }\n \n // Traverse both the LL while linking heads of both LL\n ListNode *next1 = h1->next, *next2 = h2->next;\n while(h1 != NULL && h2 != NULL){\n next1 = h1->next;\n next2 = h2->next;\n\n h1->next = h2;\n h2->next = next1;\n\n h1 = next1;\n h2 = next2;\n }\n }\n};\n\n// Solution 2 - With stack\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n // base case\n if(head->next == NULL || head->next->next == NULL) \n return ;\n \n // Step 1 - Find middle of the LL with slow-fast pointer approach\n ListNode* slow= head, *fast= head;\n stack<ListNode*> st;\n while(fast!=NULL && fast->next!=NULL){\n slow= slow->next;\n fast = fast->next->next;\n }\n \n // Step 2 - Split the LL into 2 parts from the middle\n ListNode* h2;\n if(fast != NULL)\n h2 = slow->next; \n else \n h2 = slow;\n \n // Step 3 - Push the second LL into a stack so that the last element remains at top\n while(h2!=NULL){\n st.push(h2);\n h2 = h2->next; \n }\n fast = head;\n \n // Step 4 - Link the first node with the last node and then pop the stack\n while(st.size()){ \n h2 = fast->next; \n fast->next = st.top();\n st.top()->next = h2;\n fast = h2;\n st.pop(); \n }\n\n slow->next = NULL;\n }\n};\n\n// Solution 3 - Recursion\nclass Solution {\npublic:\n void reorderList(ListNode* head) {\n //base case\n if(head!=NULL || head->next!=NULL || !head->next->next!= NULL) \n return;\n \n //Find the penultimate node i.e second last node of the linkedlist\n ListNode* penultimate = head;\n while (penultimate->next->next) \n penultimate = penultimate->next;\n \n // Link the penultimate node with the second node\n penultimate->next->next = head->next;\n head->next = penultimate->next;\n \n // Set the penultimate to the the last \n penultimate->next = NULL;\n \n // Recursive call\n reorderList(head->next->next);\n }\n};\n```
| 8 | 0 |
['Linked List', 'Two Pointers', 'Stack', 'Recursion', 'C++']
| 2 |
reorder-list
|
Detailed and Easy Python Solution for noobs like me :)
|
detailed-and-easy-python-solution-for-no-ikqz
|
Question\n\nYou are given the head of a singly linked list. The list can be represented as:\n\n\nL0 \u2192 L1 \u2192 \u2026 \u2192 Ln - 1 \u2192 Ln\n\n\nReorder
|
ebaad96
|
NORMAL
|
2022-06-01T20:29:25.860315+00:00
|
2022-06-04T20:56:57.154439+00:00
| 643 | false |
### Question\n\nYou are given the head of a singly linked list. The list can be represented as:\n\n```\nL0 \u2192 L1 \u2192 \u2026 \u2192 Ln - 1 \u2192 Ln\n```\n\n*Reorder the list to be on the following form:*\n\n```\nL0 \u2192 Ln \u2192 L1 \u2192 Ln - 1 \u2192 L2 \u2192 Ln - 2 \u2192 \u2026\n\n```\n\nYou may not modify the values in the list\'s nodes. Only nodes themselves may be changed.\n\n```\nInput: head = [1,2,3,4]\nOutput: [1,4,2,3]\n\nInput: head = [1,2,3,4,5]\nOutput: [1,5,2,4,3]\n```\n\n### Brainstorming.\n\n1. L0 \u2192 L1 \u2192 \u2026 \u2192 Ln - 1 \u2192 Ln covert to \u2014> L0 \u2192 Ln \u2192 L1 \u2192 Ln - 1 \u2192 L2 \u2192 Ln - 2 \u2192\n 1. FirstElement \u2014> lastElement \u2014> Second Element \u2014> Second LastElement\n \n ```python\n \n 1->2->3->4. to 1->4->2->3\n \n \n How will we approach this situation, we have a linked list and we have to merge\n in a way that it comes to something like this.\n FirstElement \u2014> lastElement(n-1) \u2014> Second Element \u2014> Second LastElement(n-2) ...\n \n If we look at the final output we can see they look something like two arrays \n being merged based on the same indexes.\n [1,2] [4,3]--this is the reverse of the second half of the list\n ^. ^\n \n we are merging the first element from array one and then taking the second element\n from array 2 and merging them into a new array.\n first Step\n [1,2] [4,3]\n ^. ^\n 1->4\n Second Step\n [1,2] [4,3]\n ^. ^\n 1->4->2->3\n \n This is the intuition we will be using to solve the problem.\n \n Making two arrays out of the linkedList and then joining one with the other in \n reverse order.\n \n Since we are in a linked list we have no idea what is the lenght of an array.\n ```\n \n2. How can we find the lenght of the array and also its half if we need to make that merger.\n \n ```python\n How can we use pointers\n 1->2->3->4\n ^ ^\n s. f\n \n imagine we have a slow pointer and a fast pointer. The fast pointer goes twice as\n fast as the slow pointer. When the fast pointer reaches the end of the array, where \n will the fast pointer be? half Way!\n \n First\n 1->2->3->4\n ^ ^\n s. f\n \n Second\n 1->2->3->4\n ^ ^\n s f\n \n How ever there is one catch here, lets say that the lenght of the array is odd\n What will happen then?\n \n First\n 1->2->3->4->5\n ^ ^\n s. f\n \n Second\n 1->2->3->4->5\n ^ ^\n s f\n \n Third\n 1->2->3->4->5->None\n ^ ^\n s f\n \n In the odd case the first array will be larger than the second array by one index\n l1 = [1,2,3]\n l2 = [4,5]\n \n How can we write this in code?\n \n input : head\n \n s(slowPointer) = head\n s(fastPointer) = head.next\n \n while f and f.next: \n \n \ts = s.next\n \tf = f.next.next\n \n #secondHalfStart = second\n second = s.next\n \n ```\n \n3. Now we know where the second half of the list begins how can we use that information?\n 1. [reverse a linked list](https://www.notion.so/reverse-a-linked-list-6ff7e58a12d346e9a9645057dae75e26) reference and detail for reversing a linked list and why we will use a temp varaible\n \n ```python\n 1->2->3->4\n ^\n second\n \n What if we start from the half and reverse the list after it.\n \n 1->2<-3<-4-None\n ^\n second Pointer is now at the end\n \n 1->2<-3<-4\n \n Code\n #reverse the second Half \n #setting s to none as well, so when the we are merging the two list we know\n # where the array ends and become two seprate array.\n 1->2->None <-3<-4<-None\n \n prev,s.next = None \n while second:\n \ttemp = second.next\n \tsecond.next = prev\n \tprev = second\n \tsecond = temp\n \n #the second half has been reversed.\n \n ```\n \n4. How will we merge these two lists we have\n \n ```python\n Now have the array we can start with two sides and keep merging them\n \n First Iteration\n 1->2->None None<-3<-4 to 1->4\n ^. ^ \t\t\t\t\t\t\t\t\t\t\n First Second \n \n Second iteration\n \n First Iteration\n 1->2->None None<-3<-4 to 1->4->2->3\n ^. ^ \t\t\t\t\t\t\t\t\t\t\n First Second \n \n We are done! now we can write the code.\n \n first, second = head, prev\n \n while second:\n \t\ttemp1, temp2 = first.next, second.next\n \n \t\tfirst.next = second\n \t\tsecond.next = temp1\n \t\tfirst = temp1 \n \t\tsecond = temp2 \n \n ```\n \n5. Lets code now\n \n ```python\n # Definition for singly-linked list.\n # class ListNode:\n # def __init__(self, val=0, next=None):\n # self.val = val\n # self.next = next\n class Solution:\n def reorderList(self, head: Optional[ListNode]) -> None:\n """\n Do not return anything, modify head in-place instead.\n """\n \n # find the half\n slow, fast = head, head.next\n \n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n \n half = slow.next\n slow.next = None\n prev = None\n \n # Reverse the second half\n \n while half:\n temp = half.next\n half.next = prev \n prev = half\n half = temp\n \n \n # merge the two lists\n \n first, second = head, prev\n \n while second:\n temp1, temp2 = first.next, second.next\n \n first.next = second\n second.next = temp1\n first = temp1\n second = temp2\n ```
| 8 | 0 |
['Python']
| 2 |
reorder-list
|
Easy recursive solution in C++
|
easy-recursive-solution-in-c-by-btanisha-pn4t
|
Approach: Add the last node in front of the first and then recurse for the next to next node\n\nvoid reorderList(ListNode* head) \n {\n\t\n\t //in case of
|
btanisha
|
NORMAL
|
2022-02-04T17:49:04.499833+00:00
|
2022-02-04T17:49:04.499874+00:00
| 516 | false |
Approach: Add the last node in front of the first and then recurse for the next to next node\n```\nvoid reorderList(ListNode* head) \n {\n\t\n\t //in case of a list with <=2 nodes, no change is required\n if(head==nullptr || head->next==nullptr || head->next->next==nullptr)\n return;\t\n\t\t\n\t\t//last here is actually the 2nd last node of the list\n ListNode *last=head;\n while(last->next->next) \n last=last->next;\n\t\t\t\n\t\t//moving the last node right next to the front node\n last->next->next=head->next;\n head->next=last->next;\n last->next=nullptr;\n reorderList(head->next->next);\n }\n```
| 8 | 0 |
['Recursion', 'C']
| 1 |
reorder-list
|
✔️ [Python3] ONE PASS, L(・o・)」, Explained
|
python3-one-pass-lo-explained-by-artod-z0rl
|
Honestly, it\'s one and a half pass \uD83E\uDD25. So the first half pass we do to find the middle of the list. For that, we use the slow and fast pointers techn
|
artod
|
NORMAL
|
2021-12-22T02:57:08.222270+00:00
|
2021-12-22T02:59:43.801672+00:00
| 843 | false |
Honestly, it\'s one and a half pass \uD83E\uDD25. So the first half pass we do to find the middle of the list. For that, we use *the slow and fast pointers* technic. The slow one moves one node at a time, and the fast one - two nodes at a time. When the fast one riches the end of the list, the slow one points to the middle point of the list. \n\nFrom the found middle node, we start our second half pass. We detach the left part of the list from the right part and reverse the right part so that the tail would become a head of the right part: `head0 -> head1 -> ... x ... <- tail1 <- tail0`\n\nNow we do the third half pass. We iterate over two resulting lists at the same time, and connect nodes as asked in the problem: `head0 -> tail0 -> head1 -> tail1 -> ...`.\n\nTime: **O(n)** - linear for scan\nSpace: **O(1)** - store nothing\n\nRuntime: 84 ms, faster than **94.16%** of Python3 online submissions for Reorder List.\nMemory Usage: 23.2 MB, less than **94.94%** of Python3 online submissions for Reorder List.\n\n```\nclass Solution:\n def reorderList(self, head: Optional[ListNode]) -> None:\n if not head.next or not head.next.next:\n return\n \n # search for the middle\n slow, fast = head, head\n while fast.next and fast.next.next:\n slow = slow.next\n fast = fast.next.next\n\n tail, cur = None, slow.next\n slow.next = None # detach list on the middle\n \n # reverse right part\n while cur:\n cur.next, tail, cur = tail, cur, cur.next\n \n\t\t# rearrange nodes as asked\n headCur, headNext = head, head.next\n tailCur, tailNext = tail, tail.next\n while True:\n headCur.next, tailCur.next = tailCur, headNext\n \n if not tailNext:\n return\n \n tailCur, headCur = tailNext, headNext\n tailNext, headNext = tailNext.next, headNext.next\n```
| 8 | 3 |
['Python3']
| 2 |
reorder-list
|
C / C++. faster than 97.61%. O(n), Super simple & clear solution.
|
c-c-faster-than-9761-on-super-simple-cle-youy
|
\tclass Solution {\n\tpublic:\n\t\tvoid reorderList(ListNode head) {\n\t\t\tif ( ! head ) return;\n\t\t\tListNode slow = head, fast = head;\n\t\t\twhile ( fast-
|
m-d-f
|
NORMAL
|
2021-02-10T20:38:18.219446+00:00
|
2021-02-10T20:38:18.219488+00:00
| 1,456 | false |
\tclass Solution {\n\tpublic:\n\t\tvoid reorderList(ListNode* head) {\n\t\t\tif ( ! head ) return;\n\t\t\tListNode *slow = head, *fast = head;\n\t\t\twhile ( fast->next && fast->next->next )\n\t\t\t{\n\t\t\t\tslow = slow->next;\n\t\t\t\tfast = fast->next->next;\n\t\t\t}\n\t\t\t\t\n\t\t\t\n\t\t\tListNode *prev = NULL, *cur = slow->next, *save;\n\t\t\twhile ( cur )\n\t\t\t{\n\t\t\t\tsave = cur->next;\n\t\t\t\tcur->next = prev;\n\t\t\t\tprev = cur;\n\t\t\t\tcur = save;\n\t\t\t}\n\t\t\t\t\n\t\t\tslow->next = NULL;\n\t\t\t\n\t\t\tListNode *head2 = prev;\n\t\t\twhile ( head2 )\n\t\t\t{\n\t\t\t\tsave = head->next;\n\t\t\t\thead->next = head2;\n\t\t\t\thead = head2;\n\t\t\t\thead2 = save;\n\t\t\t} \n\t\t}\n\t};
| 8 | 0 |
['Linked List', 'C', 'C++']
| 2 |
reorder-list
|
💡JavaScript Solution
|
javascript-solution-by-aminick-1ikq
|
The idea\n1. Split the linked list from the middle using 2 pointers into part1& part2\n2. Reverse part2\n3. Merge part1 and part2\njavascript\n/**\n * @param {L
|
aminick
|
NORMAL
|
2020-01-07T04:47:28.373847+00:00
|
2020-01-07T04:47:28.373894+00:00
| 1,102 | false |
### The idea\n1. Split the linked list from the middle using 2 pointers into part1& part2\n2. Reverse part2\n3. Merge part1 and part2\n``` javascript\n/**\n * @param {ListNode} head\n * @return {void} Do not return anything, modify head in-place instead.\n */\nvar reorderList = function(head) {\n \n if (!head || !head.next) return; \n \n // find the middle point\n let slow=head, fast=head;\n while(fast.next && fast.next.next) {\n slow = slow.next;\n fast = fast.next.next;\n }\n \n // split into two part head & part2\n let part2 = slow.next;\n slow.next = null;\n \n // reverse part 2\n let prev = null, cur = part2, next = cur.next;\n while(cur) {\n next = cur.next;\n cur.next = prev;\n prev = cur;\n cur = next;\n }\n \n part2 = prev;\n \n // merge head & part2\n while(head && part2) {\n let p1 = head.next;\n let p2 = part2.next\n head.next = part2;\n head.next.next = p1;\n part2 = p2;\n head = p1;\n }\n \n return head;\n};\n```
| 8 | 0 |
['JavaScript']
| 0 |
reorder-list
|
2ms Recursive Java Solution
|
2ms-recursive-java-solution-by-sovietace-vhn1
|
\nclass Solution {\n public void reorderList(ListNode head) {\n if (head == null) {\n return;\n }\n \n tail(head, head
|
sovietaced
|
NORMAL
|
2018-09-03T19:26:13.309495+00:00
|
2018-09-03T19:26:13.309540+00:00
| 688 | false |
```\nclass Solution {\n public void reorderList(ListNode head) {\n if (head == null) {\n return;\n }\n \n tail(head, head); \n }\n \n // Performs tail end recursion. Starts inserting nodes into the first half once we find the end. \n private ListNode tail(ListNode head, ListNode curr) {\n // Recurse until we find the tail\n if (curr.next != null) {\n head = tail(head, curr.next);\n }\n \n // Insertions complete. Stop\n if (head == null) {\n return null;\n }\n\n ListNode second = head.next;\n \n // Check to see if we\'ve reached the end of the new merged linked list\n if (head == curr || curr == second) {\n // Make sure to terminate the linked list\n curr.next = null;\n return null;\n }\n \n // Insert node from end (curr) between head and second\n // head -> curr -> second\n head.next = curr; \n curr.next = second;\n \n // Return where the next insertion should begin\n return second;\n }\n}\n```
| 8 | 1 |
[]
| 3 |
reorder-list
|
Neat and clean code|| no need of explanation
|
neat-and-clean-code-no-need-of-explanati-mjve
|
Write the space complexity in the comment section. I will update it later. Let\'s see whose answer is correct.\n# Complexity\n- Time complexity:O(n)\n Add your
|
Akshaypundir7579
|
NORMAL
|
2024-03-23T03:22:08.127327+00:00
|
2024-03-23T04:24:05.138777+00:00
| 1,210 | false |
# Write the space complexity in the comment section. I will update it later. Let\'s see whose answer is correct.\n# Complexity\n- Time complexity:O(n)\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``` c++ []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* reverse(ListNode* head){\n ListNode*prev=NULL,*next=head;\n while(head){\n next=head->next;\n head->next=prev;\n prev=head;\n head=next;\n }\n return prev;\n }\n\n ListNode* merge(ListNode* h1,ListNode* h2){\n if(h1==NULL)return h2;\n if(h2->next==NULL)return h1;\n h1->next=merge(h2,h1->next);\n return h1;\n }\n\n ListNode* findmid(ListNode* head){\n ListNode* slow=head,*fast=head;\n while(fast&&fast->next){\n slow=slow->next;\n fast=fast->next->next;\n }\n return slow;\n }\n void reorderList(ListNode* head) {\n if(head==NULL||head->next==NULL)return;\n\n ListNode* mid=findmid(head);\n ListNode* head_of_revll=reverse(mid);\n merge(head,head_of_revll);\n }\n};\n```\n
| 7 | 0 |
['C++']
| 4 |
reorder-list
|
143: Solution with step by step explanation
|
143-solution-with-step-by-step-explanati-yic4
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nTo reorder the linked list we can follow the below steps:\n\n1. Find the
|
Marlen09
|
NORMAL
|
2023-02-19T12:24:45.936279+00:00
|
2023-02-19T12:24:45.936308+00:00
| 2,590 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTo reorder the linked list we can follow the below steps:\n\n1. Find the middle node of the linked list using slow and fast pointer approach.\n2. Reverse the second half of the linked list.\n3. Merge the first half and the reversed second half of the linked list alternatively.\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nBeats\n94.68% O(1)\n\n# Code\n```\nclass Solution:\n def reorderList(self, head: ListNode) -> None:\n """\n Do not return anything, modify head in-place instead.\n """\n if not head or not head.next:\n return\n \n # Step 1: Find the middle of the linked list\n slow, fast = head, head.next\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n \n # Step 2: Reverse the second half of the linked list\n curr, prev = slow.next, None\n slow.next = None # set the next of the slow to None to break the link\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n second_half = prev\n \n # Step 3: Merge the first half and the reversed second half of the linked list\n first_half = head\n while first_half and second_half:\n temp1, temp2 = first_half.next, second_half.next\n first_half.next = second_half\n second_half.next = temp1\n first_half, second_half = temp1, temp2\n\n```
| 7 | 0 |
['Linked List', 'Two Pointers', 'Stack', 'Python', 'Python3']
| 2 |
reorder-list
|
GREAT JAVA EXPLAINATION
|
great-java-explaination-by-callmecomder-l0q2
|
class Solution {\n public void reorderList(ListNode head) {\n Stack s=new Stack<>();\n ListNode curr=head; //take pointer to store address of hea
|
callmecomder
|
NORMAL
|
2022-11-02T06:55:57.407139+00:00
|
2022-11-02T06:55:57.407178+00:00
| 1,435 | false |
# class Solution {\n public void reorderList(ListNode head) {\n Stack<ListNode> s=new Stack<>();\n ListNode curr=head; //take pointer to store address of head\n int c=0;\n while(curr!=null)\n {\n s.push(curr); //push address of head in stack\n curr=curr.next;\n c++; //count elements in stack or list\n }\n curr=head; //refer example at end for great explaination\n for(int i=0;i<(c/2);i++) //the loop is run to the half of the list to connect the list and stack\n {\n ListNode temp=curr.next; //take temp= address of value 2\n ListNode end=s.pop(); //take address of 4 in end node\n curr.next=end; //connect 1 with end (4)\n end.next=temp; //connect end(4) with temp(2)\n curr=temp; //pass address of temp to current to repeat the process till the end of list\n }\n curr.next=null;\n }\n}\n// Input: head = [1,2,3,4]\n// Output: [1,4,2,3]
| 7 | 0 |
['Stack', 'Java']
| 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.