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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
minimum-initial-energy-to-finish-tasks | 3 liner using parallel Sort, parallel Prefix and parallel Stream. Fastest for huge arrays. | 3-liner-using-parallel-sort-parallel-pre-a0z1 | Intuition\nSort the array by difference between required minimum and consumptuon.\n\n# Approach\nFind the cumulative sum for total consumption with parallelPref | codesinthedark | NORMAL | 2024-04-19T13:34:05.386132+00:00 | 2024-04-19T13:34:05.386154+00:00 | 21 | false | # Intuition\nSort the array by difference between required minimum and consumptuon.\n\n# Approach\nFind the cumulative sum for total consumption with parallelPrefix function. After that check the maximum difference between the current cumullative consumption and minumum required energy and add that to the total consumptuon.\n\n# Complexity\n- Time complexity:\n$$O(n \\cdot log(n))$$ - for sorting\n\n- Space complexity:\n$$O(1)$$ - we use original array so no extra space\n\n# Code\n```\nclass Solution {\n public int minimumEffort(int[][] tasks) {\n Arrays.parallelSort(tasks, (a, b)-> Integer.compare(a[1]-a[0], b[1]-b[0]));\n Arrays.parallelPrefix(tasks, (a, b) -> {int[] c = new int[2]; c[0]= b[0]+a[0]; c[1] = b[1]; return c;});\n return tasks[tasks.length-1][0] + Arrays.stream(tasks).parallel().mapToInt(t-> t[1]-t[0]).max().getAsInt();\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
minimum-initial-energy-to-finish-tasks | One Liner | one-liner-by-yoongyeom-z89d | Code\n\nclass Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n return reduce(lambda x, y: max(x, y[0])+y[1], sorted([(tasks[i][1] | YoonGyeom | NORMAL | 2024-04-16T09:45:21.531889+00:00 | 2024-04-16T09:45:21.531906+00:00 | 30 | false | # Code\n```\nclass Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n return reduce(lambda x, y: max(x, y[0])+y[1], sorted([(tasks[i][1]-tasks[i][0], tasks[i][0]) for i in range(len(tasks))]), 0)\n#easy to read\n\'\'\'\nclass Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n for i in range(len(tasks)):\n tasks[i] = tasks[i][1]-tasks[i][0], tasks[i][0]\n tasks.sort()\n cur = 0\n for i in range(len(tasks)):\n cur = max(cur, tasks[i][0])\n cur += tasks[i][1]\n return cur\n\'\'\'\n``` | 0 | 0 | ['Python3'] | 0 |
minimum-initial-energy-to-finish-tasks | C++ || very simple sorting solution || 🚀🚀 beats 90% 🚀🚀 | c-very-simple-sorting-solution-beats-90-dqobf | \n# Code\n\nclass Solution {\npublic:\n bool static cmp(const vector<int>& v1, const vector<int>& v2) {\n int abs1 = abs(v1[1] - v1[0]), abs2 = abs(v2 | Adnan_Alkam | NORMAL | 2024-04-10T01:57:37.588535+00:00 | 2024-04-10T01:57:37.588556+00:00 | 7 | false | \n# Code\n```\nclass Solution {\npublic:\n bool static cmp(const vector<int>& v1, const vector<int>& v2) {\n int abs1 = abs(v1[1] - v1[0]), abs2 = abs(v2[1] - v2[0]);\n return (abs1 == abs2)? v1[1] > v2[1] : abs1 > abs2; \n }\n int minimumEffort(vector<vector<int>>& tasks) {\n ios_base::sync_with_stdio(false);\n\t\tcin.tie(NULL);\n\t\tcout.tie(NULL);\n\n //we sort based on the difference between initial required energy and energy needed to finish the task\n sort(tasks.begin(), tasks.end(), cmp);\n //total amount of enery spent and the current amount of energy we have\n int ans = 0, current = 0;\n\n for (auto task : tasks) {\n //if we dont have enough energy\n if (current < task[1]) {\n //add the energy required the start the task\n int diff = task[1] - current;\n ans += diff, current += diff;\n }\n //spend the amount of energy to finish the task\n current -= task[0];\n }\n\n return ans;\n }\n};\n``` | 0 | 0 | ['Greedy', 'Sorting', 'C++'] | 0 |
minimum-initial-energy-to-finish-tasks | Greedy + Binary search | greedy-binary-search-by-art3mis_8-88zv | Intuition\nso the minimum must lie between the maximum minimum energy required and the sum of all minimum energy required for all tasks. \ntricky part is to sor | Art3mis_8 | NORMAL | 2024-03-05T17:06:47.399321+00:00 | 2024-03-05T17:06:47.399353+00:00 | 37 | false | # Intuition\nso the minimum must lie between the maximum minimum energy required and the sum of all minimum energy required for all tasks. \ntricky part is to sort them in a way that the higher minimum energy required task is done first.\nhence we sort by difference.\n\n# Approach\nGreedy + Binary search\n\n# Code\n```\nclass Solution {\npublic:\n bool check(int m, vector<vector<int>>&tasks){\n int rem=m;\n for(int i=0;i<tasks.size();i++){\n if(rem>=tasks[i][1]) rem-=tasks[i][0];\n else return false;\n }\n return true;\n \n }\n int minimumEffort(vector<vector<int>>& tasks) {\n sort(tasks.begin(),tasks.end(), [&](vector<int>a, vector<int>b){\n return a[1]-a[0]>b[1]-b[0];\n });\n int maxi= INT_MIN;\n for(int i=0;i<tasks.size();i++) maxi=max(maxi,tasks[i][1]);\n int low=maxi;\n int high=0;\n int ans;\n for(int i=0;i<tasks.size();i++) high+= tasks[i][1];\n while(low<=high){\n int mid=(low+high)/2;\n if(check(mid,tasks)) {\n ans=mid;\n high=mid-1;\n }\n else low=mid+1;\n }\n return ans;\n \n }\n\n};\n``` | 0 | 0 | ['Binary Search', 'Greedy', 'C++'] | 0 |
minimum-initial-energy-to-finish-tasks | very simple java maxHeap O(nlogn) | very-simple-java-maxheap-onlogn-by-ap56-ijpw | Intuition\nYou can simulate the optimal run by ranking each task and going through them accordingly. Build up the required minimal energy for the simulation and | ap56 | NORMAL | 2024-02-26T10:47:31.971605+00:00 | 2024-02-26T10:47:31.971622+00:00 | 12 | false | # Intuition\nYou can simulate the optimal run by ranking each task and going through them accordingly. Build up the required minimal energy for the simulation and that will be the answer. \n\n# Approach\nRank each task based on: energy required to start - actual energy cost\nUse a maxHeap to store these rankings and facilitate the simulation\nUse "ans" to keep track of all the energy we\'ve ever needed to add\nUse "currEnergy" to keep track of current energy as we simulate\nAdd minimum amount needed to keep going to "ans" if "currEnergy" is ever not enough\nGo through each task in maxHeap\nreturn "ans"\n\n# Complexity\n- Time complexity:\nO(nlogn), n = number of tasks all of which are added and removed from maxHeap\n\n- Space complexity:\nO(n), n = number of tasks to put in maxHeap\n\n# Code\n```\nclass Solution {\n public int minimumEffort(int[][] tasks) \n {\n PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> \n {\n int diffA = a[1] - a[0];\n int diffB = b[1] - b[0];\n return Integer.compare(diffB, diffA); \n });\n for (int[] task : tasks) maxHeap.offer(task);\n int ans = 0;\n int currEnergy = 0;\n while (!maxHeap.isEmpty())\n {\n int[] currTask = maxHeap.poll();\n if (currTask[1] > currEnergy)\n {\n ans += (currTask[1] - currEnergy);\n currEnergy = currTask[1];\n }\n currEnergy -= currTask[0];\n }\n return ans;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
minimum-initial-energy-to-finish-tasks | Python binary search | python-binary-search-by-saiganesh123-z1fn | ```\nclass Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n tasks.sort(key=lambda x:x[1]-x[0] ,reverse=True)\n n=l | SaiGanesh123 | NORMAL | 2024-02-23T15:03:20.566377+00:00 | 2024-02-23T15:03:20.566401+00:00 | 7 | false | ```\nclass Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n tasks.sort(key=lambda x:x[1]-x[0] ,reverse=True)\n n=len(tasks)\n l=1\n h=10**10\n while l<=h:\n mid=(l+h)//2\n ans=mid\n flag=True\n for i in range(n):\n if ans>=tasks[i][1]:\n ans-=tasks[i][0]\n else:\n flag=False\n\n if flag:\n h=mid-1\n else:\n l=mid+1\n return l | 0 | 0 | ['Binary Tree', 'Python'] | 0 |
minimum-initial-energy-to-finish-tasks | Greedy || C++ | greedy-c-by-scraper_nerd-vtl1 | \n# Code\n\nclass Solution {\npublic:\n int minimumEffort(vector<vector<int>>& tasks) {\n sort(tasks.begin(),tasks.end(),[](const vector<int>&a,const | Scraper_Nerd | NORMAL | 2024-02-19T08:32:48.652340+00:00 | 2024-02-19T08:32:48.652370+00:00 | 9 | false | \n# Code\n```\nclass Solution {\npublic:\n int minimumEffort(vector<vector<int>>& tasks) {\n sort(tasks.begin(),tasks.end(),[](const vector<int>&a,const vector<int>& b){\nreturn (a[1]-a[0])>(b[1]-b[0]);});\n int ans=0;\n int intial=0;\n for(int i=0;i<tasks.size();i++){\n if(intial<tasks[i][1]){\n ans+=tasks[i][1]-intial;\n intial=tasks[i][1];\n }\n intial-=tasks[i][0];\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Greedy', 'Sorting', 'C++'] | 0 |
minimum-initial-energy-to-finish-tasks | Easy Solution | easy-solution-by-prakash_phagami-s3p5 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe intiuition of the solution is to solve the problem using python programming languag | Prakash_Phagami | NORMAL | 2024-02-16T22:20:29.375585+00:00 | 2024-02-16T22:20:29.375612+00:00 | 1 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intiuition of the solution is to solve the problem using python programming language.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n def minimumEffort(self, tasks):\n """\n :type tasks: List[List[int]]\n :rtype: int\n """\n tasks.sort(key=lambda x: x[0] - x[1]) \n answer = current = 0\n for energy_cost, energy_min in tasks:\n if energy_min > current:\n answer += (energy_min - current)\n current = energy_min\n current -= energy_cost\n return answer\n\n``` | 0 | 0 | ['Python'] | 0 |
minimum-initial-energy-to-finish-tasks | simple intuitive sort and count, a minumum effort solution heheh | simple-intuitive-sort-and-count-a-minumu-5fk3 | Intuition\nUse some math intuition (or try several stategies to pass the test cases) to realize that the optimal order to complete tasks is starting with the ta | sdvorchin | NORMAL | 2024-02-08T21:41:17.294777+00:00 | 2024-02-08T21:41:17.294811+00:00 | 6 | false | # Intuition\nUse some math intuition (or try several stategies to pass the test cases) to realize that the optimal order to complete tasks is starting with the tasks that have the highest difference of `minimum[i] - actual[i]`. Then just straigh up calculate how much energy you need to complete them in that order.\n\n# Approach\nSort the tasks. Initialize current energy and the minimum starting amount to the `minimum[0]` or 0. Iterate through tasks. If at any point you don\'t have enough energy to start, add the needed amount to your current energy and the minimum starting amount. If after completing a task you have negative energy, restore it and also add the restore cost to the minimum starting amount.\n\n# Complexity\n- Time complexity:\n$$O(n* log(n))$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\n/**\n * @param {number[][]} tasks\n * @return {number}\n */\nvar minimumEffort = function(tasks) {\n tasks.sort((a, b) => (b[1] - b[0]) - (a[1] - a[0]));\n console.log(tasks);\n let ans = tasks[0][1];\n let cur = ans;\n for (let task of tasks) {\n const add1 = Math.max(0, task[1] - cur);\n cur += add1;\n ans += add1;\n\n cur -= task[0];\n const add2 = Math.max(0, -cur);\n cur += add2;\n ans += add2;\n }\n return ans;\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
minimum-initial-energy-to-finish-tasks | Optimized Greedy approach without binary search | optimized-greedy-approach-without-binary-uh91 | Intuition\nsorting with respect to absolute difference between task[i][0] and task[i][1] will work.\n\n# Approach\nsorting with respect to absolute difference b | harshvardhanofficial2001 | NORMAL | 2024-02-06T23:20:00.690890+00:00 | 2024-02-06T23:20:00.690921+00:00 | 0 | false | # Intuition\nsorting with respect to absolute difference between task[i][0] and task[i][1] will work.\n\n# Approach\nsorting with respect to absolute difference between task[i][0] and task[i][1] will work.\nthen we can use binary search for getting answer or we can maintain a sum variable with task[i][0] and take maximum out of it.\n\n# Complexity\n- Time complexity:\nO(n*log(n))\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int minimumEffort(vector<vector<int>>& t) {\n sort(t.begin(),t.end(),[&] (vector<int>&a,vector<int>&b){\n return abs(a[0]-a[1])>abs(b[0]-b[1]);\n });\n int sum=0,ans=0;\n for(int i=0;i<t.size();i++){\n ans=max(ans,sum+t[i][1]);\n ans=max(ans,sum+t[i][0]);\n sum+=t[i][0];\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-initial-energy-to-finish-tasks | Greedy approach with sorting | greedy-approach-with-sorting-by-rabusta-mzv0 | Approach\nSort descending by difference between spend and requare\n\n# Complexity\n- Time complexity: O(nlog(n))\n Add your time complexity here, e.g. O(n) \n\n | rabusta | NORMAL | 2024-02-06T16:15:50.420109+00:00 | 2024-02-06T16:15:50.420131+00:00 | 1 | false | # Approach\nSort descending by difference between spend and requare\n\n# Complexity\n- Time complexity: $$O(nlog(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```\nimport kotlin.math.*\n\nclass Solution {\n fun minimumEffort(tasks: Array<IntArray>): Int {\n \n tasks.sortByDescending { abs(it[0] - it[1]) }\n var ans = tasks[0][1]\n var cur = tasks[0][1]\n for (i in 0..tasks.size-1) {\n cur -= tasks[i][0]\n if (i < tasks.size-1 && cur < tasks[i+1][1]) {\n ans += tasks[i+1][1] - cur\n cur = tasks[i+1][1]\n }\n }\n\n return ans\n }\n}\n``` | 0 | 0 | ['Greedy', 'Sorting', 'Kotlin'] | 0 |
minimum-initial-energy-to-finish-tasks | [C] | Solution with comments and description | c-solution-with-comments-and-description-fe4w | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nAs our aim is to use as | ElsJon | NORMAL | 2024-01-22T20:00:12.579514+00:00 | 2024-01-22T20:00:12.579546+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nAs our aim is to use as little starting energy as possible, as little energy as possible must be left over after the last task has been completed. This specifically means that the last task performed must have the smallest difference between \'minimum\' and \'actual\'.\n\nStep 1 follows from this: Sort the array according to \'minimum\' - \'actual\'.\n## Let us now start at index 0: \nIt is known that you need at least tasks[0][1] energy to execute the task -> start value of our energy counter\n\n## Continue with index 1:\nSince we lose at least task[1][0] energy when performing task[1], we add this to our energy counter. However, if this value is below the minimum task[1][1], the task cannot be started and the energy before the task must therefore be tasks[1][1].\n\n## Next\nThis process is now applied to the entire array.\n\nTranslated with DeepL.com (free version)\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nint compare(const void *a, const void *b) {\n const int **ia = (const int **)a;\n const int **ib = (const int **)b;\n\n return ((*ia)[1] - (*ia)[0]) - ((*ib)[1]-(*ib)[0]);\n}\n\nint minimumEffort(int** tasks, int tasksSize, int* tasksColSize) {\n int ans;\n\n //Sorts the Array by minimum-actual\n qsort(tasks, tasksSize, sizeof(tasks[0]), compare);\n\n //starting value at index 0\n ans = tasks[0][1];\n\n for (int i = 1; i < tasksSize; ++i) {\n if (ans + tasks[i][0] >= tasks[i][1]) {\n //Adding the required Energy for the i\'th task is bigger than the minimum required to start this task\n ans += tasks[i][0];\n }\n else{\n //Adding the required Energy for the i\'th task is smaller than the minimum required to start this task\n ans = tasks[i][1];\n }\n }\n return ans;\n}\n``` | 0 | 0 | ['C'] | 0 |
minimum-initial-energy-to-finish-tasks | Python - greedy approach beats 100%/100% | python-greedy-approach-beats-100100-by-u-4hc9 | Intuition\nIt makes sense to minimize the gap between the minimum and the actual. End result of such an operation is either:\n\n1. You have >= minimum for the n | user2904n | NORMAL | 2024-01-15T00:21:17.684708+00:00 | 2024-01-15T00:21:17.684749+00:00 | 56 | false | # Intuition\nIt makes sense to minimize the gap between the minimum and the actual. End result of such an operation is either:\n\n1. You have >= minimum for the next activity. Good chance to minimize result\n2. You have < minimum for the next activity, so you just need to top-up.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n tasks.sort(key = lambda x: x[1] - x[0])\n current = 0\n result = 0\n while tasks:\n actual, minimum = tasks.pop()\n if current < minimum:\n result += minimum - current\n current = minimum\n current -= actual\n return result\n``` | 0 | 0 | ['Python3'] | 0 |
minimum-initial-energy-to-finish-tasks | Sorting, Greedy | sorting-greedy-by-mot882000-j1bf | 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 | mot882000 | NORMAL | 2024-01-02T10:50:58.054309+00:00 | 2024-01-02T10:50:58.054340+00:00 | 3 | 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)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minimumEffort(int[][] tasks) {\n\n\n // 1. \uC804\uCCB4 tasks\uB97C \uC9C4\uD589\uD558\uBA74\uC11C \uD544\uC694\uD55C totalEnergy \uB97C \uAD6C\uD55C\uB2E4. \n // tasks[][0]\uC758 \uCD1D\uD569\n \n // 2. tasks\uB97C minimum\uACFC actual \uC758 \uCC28\uC774\uAC00 \uD070 \uC21C\uC73C\uB85C \uC815\uB82C\uD55C\uB2E4. \n // \u203B \uCC28\uC774\uAC00 \uD074 \uC218\uB85D minimum\uC774 \uD06C\uACE0 actual\uC774 \uC791\uAE30 \uB54C\uBB38\uC5D0 \n // totalEnergy\uC5D0\uC11C \uC801\uAC8C \uC0AD\uC81C\uD558\uACE0 \uD070 minimum tasks\uB97C \uC6B0\uC120\uC801\uC73C\uB85C \uCC98\uB9AC\uD568\uC73C\uB85C\uC368 \n // \uCD94\uAC00\uB85C \uD544\uC694\uD55C energy(\uB0A8\uC740 totalEnergy\uC640 tasks[i][1]\uC758 \uAC12\uC758 \uCC28\uC774)\uB97C \uC801\uAC8C \uCD94\uAC00\uD560 \uC218 \uC788\uB2E4.\n\n // 3. totalEnergy \uB97C \uAE30\uBCF8 \uAC12\uC73C\uB85C (\uACB0\uACFC \uAC12\uC5D0 totalEnergy\uB97C \uB9E4\uD551\uD574\uC900\uB2E4. )\n // 2.\uC5D0\uC11C \uC815\uB82C\uB41C tasks\uB97C \uB3CC\uBA74\uC11C tasks[i][0]\uC744 totalEnergy\uC5D0\uC11C \uAC10\uC18C\uC2DC\uCF1C\uC900\uB2E4. \n // \uB9CC\uC57D, \uB0A8\uC740 totalEnergy\uBCF4\uB2E4 tasks[i][0] \uAC00 \uD06C\uB2E4\uBA74 tasks[i][0] - totalEnergy \uB9CC\uD07C \uCD94\uAC00 \uC2DC\uCF1C\uC8FC\uACE0 \n // \uCD94\uAC00 \uC2DC\uCF1C\uC900 \uAC12\uC744 \uACB0\uACFC\uC5D0\uB3C4 \uCD94\uAC00\uC2DC\uCF1C\uC900\uB2E4.\n\n // 4. \uACB0\uACFC \uAC12 \uBC18\uD658\n // \u203B minimum\uC774 \uC801\uC808\uD558\uAC8C \uC798 \uBC30\uC815\uC774 \uB418\uC5C8\uB2E4\uBA74 tasks[][0]\uC758 \uCD1D\uD569\uC774 min Energy \uC774\uC9C0\uB9CC\n // Energy\uB97C \uC0AD\uAC10\uD574 \uB098\uAC00\uBA74\uC11C \uB2E4\uC74C task\uC758 minimum \uBCF4\uB2E4 \uC791\uC544\uC9C0\uBA74 \uC9C4\uC785\uC774 \uBD88\uAC00\uB2A5\uD558\uBBC0\uB85C \uADF8\uB9CC\uD07C \uCD94\uAC00\uB97C \uD574\uC918\uC57C\uD558\uB294\uB370 \n // \uADF8 \uCD5C\uC801\uC758 \uCD94\uAC00\uAC12\uC744 \uAC00\uC838\uAC08 \uC218 \uC788\uAC8C\uB054 \uC815\uB82C\uD558\uB294 \uBC29\uBC95\uC774 2. \uC758 \uC815\uB82C \uBC29\uBC95\uC774\uB2E4. \n\n Arrays.sort(tasks, new Comparator<int[]>() {\n @Override\n public int compare(int[] arg0, int[] arg1) {\n return (arg0[1]-arg0[0])==(arg1[1]-arg1[0])?arg1[0]-arg0[0]:(arg1[1]-arg1[0])-(arg0[1]-arg0[0]);\n }\n });\n\n int totalEnergy = 0;\n\n for(int i = 0; i < tasks.length; i++) {\n totalEnergy += tasks[i][0];\n }\n\n\n int currentEnergy = totalEnergy;\n\n for(int i = 0; i < tasks.length; i++) {\n if ( tasks[i][1] > currentEnergy ){\n totalEnergy += tasks[i][1] - currentEnergy;\n currentEnergy += tasks[i][1] - currentEnergy;\n }\n currentEnergy -= tasks[i][0];\n }\n\n return totalEnergy; \n }\n}\n``` | 0 | 0 | ['Greedy', 'Sorting', 'Java'] | 0 |
remove-nth-node-from-end-of-list | JS, Python, Java, C++ | Easy Two-Pointer Solution w/ Explanation | js-python-java-c-easy-two-pointer-soluti-souf | (Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful, please upvote this post.)\n\n---\n\n#### Idea:\n | sgallivan | NORMAL | 2021-04-18T07:56:20.553662+00:00 | 2021-04-18T08:25:58.594916+00:00 | 168,962 | false | *(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful,* ***please upvote*** *this post.)*\n\n---\n\n#### ***Idea:***\n\nWith a singly linked list, the _only_ way to find the end of the list, and thus the **n**\'th node from the end, is to actually iterate all the way to the end. The challenge here is attemping to find the solution in only one pass. A naive approach here might be to store pointers to each node in an array, allowing us to calculate the **n**\'th from the end once we reach the end, but that would take **O(M) extra space**, where **M** is the length of the linked list.\n\nA slightly less naive approach would be to only store only the last **n+1** node pointers in the array. This could be achieved by overwriting the elements of the storage array in circlular fashion as we iterate through the list. This would lower the **space complexity** to **O(N+1)**.\n\nIn order to solve this problem in only one pass and **O(1) extra space**, however, we would need to find a way to _both_ reach the end of the list with one pointer _and also_ reach the **n**\'th node from the end simultaneously with a second pointer.\n\nTo do that, we can simply stagger our two pointers by **n** nodes by giving the first pointer (**fast**) a head start before starting the second pointer (**slow**). Doing this will cause **slow** to reach the **n**\'th node from the end at the same time that **fast** reaches the end.\n\n\n\nSince we will need access to the node _before_ the target node in order to remove the target node, we can use **fast.next == null** as our exit condition, rather than **fast == null**, so that we stop one node earlier.\n\nThis will unfortunately cause a problem when **n** is the same as the length of the list, which would make the first node the target node, and thus make it impossible to find the node _before_ the target node. If that\'s the case, however, we can just **return head.next** without needing to stitch together the two sides of the target node.\n\nOtherwise, once we succesfully find the node _before_ the target, we can then stitch it together with the node _after_ the target, and then **return head**.\n\n---\n\n#### ***Implementation:***\n\nThere are only minor differences between the code of all four languages.\n\n---\n\n#### ***Javascript Code:***\n\nThe best result for the code below is **60ms / 40.6MB** (beats 100% / 13%).\n```javascript\nvar removeNthFromEnd = function(head, n) {\n let fast = head, slow = head\n for (let i = 0; i < n; i++) fast = fast.next\n if (!fast) return head.next\n while (fast.next) fast = fast.next, slow = slow.next\n slow.next = slow.next.next\n return head\n};\n```\n\n---\n\n#### ***Python Code:***\n\nThe best result for the code below is **28ms / 13.9MB** (beats 92% / 99%).\n```python\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n fast, slow = head, head\n for _ in range(n): fast = fast.next\n if not fast: return head.next\n while fast.next: fast, slow = fast.next, slow.next\n slow.next = slow.next.next\n return head\n```\n\n---\n\n#### ***Java Code:***\n\nThe best result for the code below is **0ms / 36.5MB** (beats 100% / 97%).\n```java\nclass Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n ListNode fast = head, slow = head;\n for (int i = 0; i < n; i++) fast = fast.next;\n if (fast == null) return head.next;\n while (fast.next != null) {\n fast = fast.next;\n slow = slow.next;\n }\n slow.next = slow.next.next;\n return head;\n }\n}\n```\n\n---\n\n#### ***C++ Code:***\n\nThe best result for the code below is **0ms / 10.6MB** (beats 100% / 93%).\n```c++\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode *fast = head, *slow = head;\n for (int i = 0; i < n; i++) fast = fast->next;\n if (!fast) return head->next;\n while (fast->next) fast = fast->next, slow = slow->next;\n slow->next = slow->next->next;\n return head;\n }\n};\n``` | 1,502 | 11 | ['C', 'Python', 'Java', 'JavaScript'] | 56 |
remove-nth-node-from-end-of-list | Simple Java solution in one pass | simple-java-solution-in-one-pass-by-tms-onhr | A one pass solution can be done using pointers. Move one pointer fast --> n+1 places forward, to maintain a gap of n between the two pointers and then move bo | tms | NORMAL | 2015-01-09T09:53:44+00:00 | 2018-10-23T06:10:24.683471+00:00 | 179,635 | false | A one pass solution can be done using pointers. Move one pointer **fast** --> **n+1** places forward, to maintain a gap of n between the two pointers and then move both at the same speed. Finally, when the fast pointer reaches the end, the slow pointer will be **n+1** places behind - just the right spot for it to be able to skip the next node.\n\nSince the question gives that **n** is valid, not too many checks have to be put in place. Otherwise, this would be necessary.\n\n public ListNode removeNthFromEnd(ListNode head, int n) {\n \n ListNode start = new ListNode(0);\n ListNode slow = start, fast = start;\n slow.next = head;\n \n //Move fast in front so that the gap between slow and fast becomes n\n for(int i=1; i<=n+1; i++) {\n fast = fast.next;\n }\n //Move fast to the end, maintaining the gap\n while(fast != null) {\n slow = slow.next;\n fast = fast.next;\n }\n //Skip the desired node\n slow.next = slow.next.next;\n return start.next;\n\t} | 1,034 | 17 | ['Java'] | 133 |
remove-nth-node-from-end-of-list | 3 short Python solutions | 3-short-python-solutions-by-stefanpochma-x3ik | Value-Shifting - AC in 64 ms\n\nMy first solution is "cheating" a little. Instead of really removing the nth node, I remove the nth value. I recursively determi | stefanpochmann | NORMAL | 2015-05-25T00:54:07+00:00 | 2018-10-23T14:37:09.941828+00:00 | 100,670 | false | **Value-Shifting - AC in 64 ms**\n\nMy first solution is "cheating" a little. Instead of really removing the nth *node*, I remove the nth *value*. I recursively determine the indexes (counting from back), then shift the values for all indexes larger than n, and then always drop the head.\n\n class Solution:\n def removeNthFromEnd(self, head, n):\n def index(node):\n if not node:\n return 0\n i = index(node.next) + 1\n if i > n:\n node.next.val = node.val\n return i\n index(head)\n return head.next\n\n---\n\n**Index and Remove - AC in 56 ms**\n\nIn this solution I recursively determine the indexes again, but this time my helper function removes the nth node. It returns two values. The index, as in my first solution, and the possibly changed head of the remaining list.\n\n class Solution:\n def removeNthFromEnd(self, head, n):\n def remove(head):\n if not head:\n return 0, head\n i, head.next = remove(head.next)\n return i+1, (head, head.next)[i+1 == n]\n return remove(head)[1]\n\n---\n\n**n ahead - AC in 48 ms**\n\nThe standard solution, but without a dummy extra node. Instead, I simply handle the special case of removing the head right after the fast cursor got its head start.\n\n class Solution:\n def removeNthFromEnd(self, head, n):\n fast = slow = head\n for _ in range(n):\n fast = fast.next\n if not fast:\n return head.next\n while fast.next:\n fast = fast.next\n slow = slow.next\n slow.next = slow.next.next\n return head | 611 | 12 | ['Python'] | 72 |
remove-nth-node-from-end-of-list | ✅ Short & Simple One-Pass Solution w/ Explanation | Beats 100% | No dummy node required! | short-simple-one-pass-solution-w-explana-tybf | This problem is very similar to the 1721. Swapping Nodes in a Linked List , just that we have to remove the kth node from the end instead of swapping it.\n\n\n- | archit91 | NORMAL | 2021-04-18T07:53:46.102982+00:00 | 2021-04-18T12:17:45.001312+00:00 | 33,863 | false | This problem is very similar to the **[1721. Swapping Nodes in a Linked List](https://leetcode.com/problems/swapping-nodes-in-a-linked-list/)** , just that we have to **remove** the kth node from the end instead of swapping it.\n\n\n---\n\n\u2714\uFE0F ***Solution - I (One-Pointer, Two-Pass)***\n\nThis approach is very intuitive and easy to get. \n\n* We just iterate in the first-pass to find the length of the linked list - **`len`**.\n\n* In the next pass, iterate **`len - n - 1`** nodes from start and delete the next node (which would be *`nth`* node from end).\n\n---\n\n**C++**\n```\nListNode* removeNthFromEnd(ListNode* head, int n) {\n\tListNode* iter = head;\n\tint len = 0, i = 1;\n\twhile(iter) iter = iter -> next, len++; // finding the length of linked list\n\tif(len == n) return head -> next; // if head itself is to be deleted, just return head -> next\n\tfor(iter = head; i < len - n; i++) iter = iter -> next; // iterate first len-n nodes\n\titer -> next = iter -> next -> next; // remove the nth node from the end\n\treturn head;\n}\n```\n\n---\n\n**Python**\n```\ndef removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n\tptr, length = head, 0\n\twhile ptr:\n\t\tptr, length = ptr.next, length + 1\n\tif length == n : return head.next\n\tptr = head\n\tfor i in range(1, length - n):\n\t\tptr = ptr.next\n\tptr.next = ptr.next.next\n\treturn head\n```\n\n\n***Time Complexity :*** **`O(N)`**, where, `N` is the number of nodes in the given list. \n***Space Complexity :*** **`O(1)`**, since only constant space is used.\n\n---\n---\n\n\u2714\uFE0F ***Solution (Two-Pointer, One-Pass)***\n\nWe are required to remove the nth node from the end of list. For this, we need to traverse *`N - n`* nodes from the start of the list, where *`N`* is the length of linked list. We can do this in one-pass as follows -\n\n* Let\'s assign two pointers - **`fast`** and **`slow`** to head. We will first iterate for *`n`* nodes from start using the *`fast`* pointer. \n\n* Now, between the *`fast`* and *`slow`* pointers, **there is a gap of `n` nodes**. Now, just Iterate and increment both the pointers till `fast` reaches the last node. The gap between `fast` and `slow` is still of `n` nodes, meaning that **`slow` is nth node from the last node (which currently is `fast`)**.\n\n```\nFor eg. let the list be 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9, and n = 4.\n\n1. 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> null\n ^slow ^fast\n |<--gap of n nodes-->|\n \n => Now traverse till fast reaches end\n \n 2. 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> null\n ^slow ^fast\n |<--gap of n nodes-->|\n\t\t\t\t\t\t\n\'slow\' is at (n+1)th node from end.\nSo just delete nth node from end by assigning slow -> next as slow -> next -> next (which would remove nth node from end of list).\n```\n\n * Since we have to **delete the nth node from end of list** (And not nth from the last of list!), we just delete the next node to **`slow`** pointer and return the head.\n\n---\n\n**C++**\n```\nListNode* removeNthFromEnd(ListNode* head, int n) {\n\tListNode *fast = head, *slow = head;\n\twhile(n--) fast = fast -> next; // iterate first n nodes using fast\n\tif(!fast) return head -> next; // if fast is already null, it means we have to delete head itself. So, just return next of head\n\twhile(fast -> next) // iterate till fast reaches the last node of list\n\t\tfast = fast -> next, slow = slow -> next; \n\tslow -> next = slow -> next -> next; // remove the nth node from last\n\treturn head;\n}\n```\n\n---\n\n**Python**\n```\ndef removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n\tfast = slow = head\n\tfor i in range(n):\n\t\tfast = fast.next\n\tif not fast: return head.next\n\twhile fast.next:\n\t\tfast, slow = fast.next, slow.next\n\tslow.next = slow.next.next\n\treturn head\n```\n\n\n\n***Time Complexity :*** **`O(N)`**, where, `N` is the number of nodes in the given list. Although, the time complexity is same as above solution, we have reduced the constant factor in it to half.\n***Space Complexity :*** **`O(1)`**, since only constant space is used.\n\n---\n\n**Note :** The Problem only asks us to **remove the node from the linked list and not delete it**. A good question to ask in an interview for this problem would be whether we just need to remove the node from linked list or completely delete it from the memory. Since it has not been stated in this problem if the node is required somewhere else later on, its better to just remove the node from linked list as asked.\n\nIf we want to delete the node altogether, then we can just free its memory and point it to NULL before returning from the function.\n\n\n---\n---\n\n*Best Runtime -*\n\n<table><tr><td><img src=https://assets.leetcode.com/users/images/6c81d074-139d-4de5-96f5-5943f62a2cca_1618736585.2373421.png /></td></tr></table>\n\n\n---\n---\n\n\uD83D\uDCBB\uD83D\uDC31\u200D\uD83D\uDCBBIf there are any questions or mistakes in my post, please do comment below \uD83D\uDC47 \n\n---\n--- | 506 | 6 | ['C', 'Python'] | 24 |
remove-nth-node-from-end-of-list | 【Video】Using distance between two pointers | video-using-distance-between-two-pointer-6ais | IntuitionUsing distance between two pointers to find nth node from the last.Solution Video⭐️⭐️ Don't forget to subscribe to my channel! ⭐️⭐️■ Subscribe URL
http | niits | NORMAL | 2024-07-05T01:47:49.398342+00:00 | 2024-12-27T18:22:51.332573+00:00 | 51,659 | false | # Intuition
Using distance between two pointers to find nth node from the last.
# Solution Video
https://youtu.be/D56o6uCaVJM
### ⭐️⭐️ Don't forget to subscribe to my channel! ⭐️⭐️
**■ Subscribe URL**
http://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1
Subscribers: 4,565
Thank you for your support!
---
# Approach
A challenging point of this question is that Linked List doesn't have index number, so we don't know which node is the last Nth node from the last.
My strategy is to create `dummy` pointer and create distance `dummy` pointer and `head` pointer.
```
Input: head = [1,2,3,4,5], n = 2
```
```
[1,2,3,4,5]
d h
r
d = dummy
h = head
r = res (return value)
```
Now we move `dummy` and `head` at the same time until `head` is at the last node.
```
[1,2,3,4,5]
d h
r
[1,2,3,4,5]
d h
r
```
This example has `n = 2`, so we should remove ` node 4`. Luckily, we stop at `node 3` which is right before `node 4`. That is very important.
Why?
That's because if we stop right before target node, we can remove the target node like this.
```
dummy.next = dummy.next.next(= 5 in this case)
```
But what if we stop at the target node.
```
[1,2,3,4,5]
d h
```
It's going to be tough to remove the target node. That's why it's important to stop right before the target node.
Before we return a new list, we have one more problem. How can we return whole new list? Because `head` pointer is now the last node and `dummy` pointer is pointing to `node 3`.
```
[1,2,3,4,5]
d h
r
```
That's why at first we have `dummy` pointer and `result` pointer. The `result` pointer is still pointing to `node 1`.
All we have to do is just
```
return res.next
```
---
https://youtu.be/bU_dXCOWHls
---
# Complexity
- Time complexity: $$O(n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(1)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
```python []
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
res = ListNode(0, head)
dummy = res
for _ in range(n):
head = head.next
while head:
head = head.next
dummy = dummy.next
dummy.next = dummy.next.next
return res.next
```
```javascript []
var removeNthFromEnd = function(head, n) {
let res = new ListNode(0, head);
let dummy = res;
for (let i = 0; i < n; i++) {
head = head.next;
}
while (head) {
head = head.next;
dummy = dummy.next;
}
dummy.next = dummy.next.next;
return res.next;
};
```
```java []
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode res = new ListNode(0, head);
ListNode dummy = res;
for (int i = 0; i < n; i++) {
head = head.next;
}
while (head != null) {
head = head.next;
dummy = dummy.next;
}
dummy.next = dummy.next.next;
return res.next;
}
}
```
```C++ []
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* res = new ListNode(0, head);
ListNode* dummy = res;
for (int i = 0; i < n; i++) {
head = head->next;
}
while (head != nullptr) {
head = head->next;
dummy = dummy->next;
}
dummy->next = dummy->next->next;
return res->next;
}
};
```
# Step by Step Algorithm
1. **Initialize variables:**
- We create a dummy node `res` with a value of 0 and set its next pointer to the head of the original list. This dummy node helps in handling edge cases when removing the first node.
- We initialize another pointer `dummy` to the dummy node `res`. This pointer will be used to traverse the list.
```python
res = ListNode(0, head)
dummy = res
```
2. **Move `head` pointer forward by `n` nodes:**
- We iterate `n` times using a for loop to advance the `head` pointer `n` nodes forward. This effectively moves `head` to the nth node from the beginning.
```python
for _ in range(n):
head = head.next
```
3. **Find the node before the node to be removed:**
- We use a while loop to traverse the list with both `head` and `dummy` pointers.
- As long as `head` is not None, we move both `head` and `dummy` pointers one node forward in each iteration.
- After this loop, `dummy` will be pointing to the node right before the node to be removed.
```python
while head:
head = head.next
dummy = dummy.next
```
4. **Remove the nth node from the end:**
- Once the loop finishes, `dummy` will be pointing to the node right before the node to be removed.
- We update the `next` pointer of the node pointed by `dummy` to skip the next node, effectively removing the nth node from the end.
```python
dummy.next = dummy.next.next
```
5. **Return the modified list:**
- Finally, we return the next node after the dummy node `res`, which is the head of the modified list.
```python
return res.next
```
This algorithm effectively removes the nth node from the end of the linked list by traversing it only once.
---
Thank you for reading my post. Please upvote it and don't forget to subscribe to my channel!
### ⭐️ Subscribe URL
http://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1
https://youtu.be/8feKVQcOs28 | 481 | 0 | ['C++', 'Java', 'Python3', 'JavaScript'] | 9 |
remove-nth-node-from-end-of-list | ⚡️Beat 100.00% | ✅ Full explanation with pictures 🧩 | beat-10000-full-explanation-with-picture-sg8y | \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# Code\nPython []\nclass Solution(object):\n def removeNthFromEnd(self, head, n):\n dummy = ListNode(0)\n d | DevOgabek | NORMAL | 2024-03-03T00:59:44.244156+00:00 | 2024-03-18T06:50:39.356307+00:00 | 48,721 | false | \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# Code\n```Python []\nclass Solution(object):\n def removeNthFromEnd(self, head, n):\n dummy = ListNode(0)\n dummy.next = head\n first = dummy\n second = dummy\n\n for _ in range(n + 1):\n first = first.next\n\n while first is not None:\n first = first.next\n second = second.next\n\n second.next = second.next.next\n\n return dummy.next\n```\n```python3 []\nclass Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n dummy = ListNode(0)\n dummy.next = head\n first = dummy\n second = dummy\n\n for _ in range(n + 1):\n first = first.next\n\n while first is not None:\n first = first.next\n second = second.next\n\n second.next = second.next.next\n\n return dummy.next\n```\n```C++ []\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode* dummy = new ListNode(0);\n dummy->next = head;\n ListNode* first = dummy;\n ListNode* second = dummy;\n\n for (int i = 0; i <= n; ++i) {\n first = first->next;\n }\n\n while (first != nullptr) {\n first = first->next;\n second = second->next;\n }\n\n ListNode* temp = second->next;\n second->next = second->next->next;\n delete temp;\n\n return dummy->next;\n }\n};\n```\n```javascript []\nvar removeNthFromEnd = function(head, n) {\n const dummy = new ListNode(0);\n dummy.next = head;\n let first = dummy;\n let second = dummy;\n\n for (let i = 0; i <= n; i++) {\n first = first.next;\n }\n\n while (first !== null) {\n first = first.next;\n second = second.next;\n }\n\n second.next = second.next.next;\n\n return dummy.next;\n};\n```\n\n\n## **My solutions**\n\n\uD83D\uDFE2 - $$easy$$ \n\uD83D\uDFE1 - $$medium$$ \n\uD83D\uDD34 - $$hard$$\n\n\uD83D\uDFE1 [17. Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/solutions/4845532/there-is-an-80-chance-of-being-in-the-interview-full-problem-explanation)\n\uD83D\uDFE1 [22. Generate Parentheses](https://leetcode.com/problems/generate-parentheses/solutions/4845742/simple-explanation-with-pictures)\n\uD83D\uDFE1 [39. Combination Sum](https://leetcode.com/problems/combination-sum/solutions/4847482/beat-8292-full-explanation-with-pictures)\n\uD83D\uDFE2 [2540. Minimum Common Value](https://leetcode.com/problems/minimum-common-value/solutions/4845076/beat-9759-full-explanation-with-pictures)\n\uD83D\uDFE2 [3005. Count Elements With Maximum Frequency](https://leetcode.com/problems/count-elements-with-maximum-frequency/solutions/4839796/beat-8369-full-explanation-with-pictures)\n\uD83D\uDFE2 [3028. Ant on the Boundary](https://leetcode.com/problems/ant-on-the-boundary/solutions/4837433/full-explanation-with-pictures)\n\uD83D\uDFE2 [876. Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/solutions/4834682/beat-10000-full-explanation-with-pictures)\n\uD83D\uDFE1 [1750. Minimum Length of String After Deleting Similar Ends](https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/solutions/4824224/beat-10000-full-explanation-with-pictures)\n\uD83D\uDFE1 [948. Bag of Tokens](https://leetcode.com/problems/bag-of-tokens/solutions/4818912/beat-10000-full-explanation-with-pictures)\n\uD83D\uDFE1 [19. Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/solutions/4813340/beat-10000-full-explanation-with-pictures)\n\uD83D\uDFE2 [977. Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/solutions/4807704/square-sorter-python-python3-javascript-c)\n\uD83D\uDFE2 [2864. Maximum Odd Binary Number](https://leetcode.com/problems/maximum-odd-binary-number/solutions/4802402/visual-max-odd-binary-solver-python-python3-javascript-c)\n\uD83D\uDFE1 [1609. Even Odd Tree](https://leetcode.com/problems/even-odd-tree/solutions/4797529/even-odd-tree-validator-python-python3-javascript-c)\n\uD83D\uDFE2 [9. Palindrome Number](https://leetcode.com/problems/palindrome-number/solutions/4795373/why-not-1-line-of-code-python-python3-c-everyone-can-understand)\n\uD83D\uDFE1 [513. Find Bottom Left Tree Value](https://leetcode.com/problems/find-bottom-left-tree-value/solutions/4792022/binary-tree-explorer-mastered-javascript-python-python3-c-10000-efficiency-seeker)\n\uD83D\uDFE2 [1. Two Sum](https://leetcode.com/problems/two-sum/solutions/4791305/5-methods-python-c-python3-from-easy-to-difficult)\n\uD83D\uDFE2 [543. Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/solutions/4787634/surpassing-9793-memory-magician-excelling-at-9723)\n[More...](https://leetcode.com/DevOgabek/)\n\n | 267 | 7 | ['Linked List', 'Two Pointers', 'Python', 'C++', 'Python3', 'JavaScript'] | 38 |
remove-nth-node-from-end-of-list | Python Two Pointer solution with comments Easy to Understand | python-two-pointer-solution-with-comment-bdbh | Please upvote once you get this :)\n\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n fast = head\n slow = | joshuasol | NORMAL | 2021-01-27T20:50:40.090947+00:00 | 2021-01-27T20:50:40.090978+00:00 | 23,858 | false | Please upvote once you get this :)\n```\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n fast = head\n slow = head\n # advance fast to nth position\n for i in range(n):\n fast = fast.next\n \n if not fast:\n return head.next\n # then advance both fast and slow now they are nth postions apart\n # when fast gets to None, slow will be just before the item to be deleted\n while fast.next:\n slow = slow.next\n fast = fast.next\n # delete the node\n slow.next = slow.next.next\n return head\n``` | 234 | 1 | ['Two Pointers', 'Python', 'Python3'] | 21 |
remove-nth-node-from-end-of-list | My short C++ solution | my-short-c-solution-by-taotaou-1gls | class Solution\n {\n public:\n ListNode* removeNthFromEnd(ListNode* head, int n)\n {\n ListNode** t1 = &head, *t2 = head;\n | taotaou | NORMAL | 2014-11-24T02:17:45+00:00 | 2018-09-28T12:47:22.548416+00:00 | 68,724 | false | class Solution\n {\n public:\n ListNode* removeNthFromEnd(ListNode* head, int n)\n {\n ListNode** t1 = &head, *t2 = head;\n for(int i = 1; i < n; ++i)\n {\n t2 = t2->next;\n }\n while(t2->next != NULL)\n {\n t1 = &((*t1)->next);\n t2 = t2->next;\n }\n *t1 = (*t1)->next;\n return head;\n }\n }; | 189 | 17 | [] | 48 |
remove-nth-node-from-end-of-list | C++ solution, easy to understand with explanations. | c-solution-easy-to-understand-with-expla-ksjw | Renewed Solution \n\nThe difference between the final node and the to_be_delete node is N. And here the assumption is that n is always valid.\n\nfast pointer po | kun596 | NORMAL | 2015-01-22T11:43:28+00:00 | 2018-10-13T04:16:24.865317+00:00 | 45,989 | false | <h1>Renewed Solution</h1>\n\nThe difference between the final node and the `to_be_delete` node is N. And here the assumption is that n is <b>always</b> valid.\n\n`fast` pointer points to the node which is N step away from the `to_be_delete` node.<br>\n`slow` pointer points to the `to_be_delete` node.\n\nThe algorithms is described as below:\n\n<b>Firstly</b>, move `fast` pointer N step forward.<br>\n<b>Secondly</b>,move `fast` and `slow` pointers simultaneously <b>one step a time</b> forward till the `fast` pointer reach the end, which will cause the `slow` pointer points to the previous node of the `to_be_delete` node.\n\n<b>Finally</b>, `slow->next = slow->next->next`.\n\n ListNode *removeNthFromEnd(ListNode *head, int n) \n {\n if (!head)\n return nullptr;\n \n ListNode new_head(-1);\n new_head.next = head;\n\n ListNode *slow = &new_head, *fast = &new_head;\n\n for (int i = 0; i < n; i++)\n fast = fast->next;\n\n while (fast->next) \n {\n fast = fast->next;\n slow = slow->next;\n }\n\n ListNode *to_de_deleted = slow->next;\n slow->next = slow->next->next;\n \n delete to_be_deleted;\n\n return new_head.next;\n }\n**Fixed : Added code for deleting the N-th node.** | 171 | 2 | ['C++'] | 20 |
remove-nth-node-from-end-of-list | CLEAR JAVA SOLUTION WITH DETAILED EXPLANATION! | clear-java-solution-with-detailed-explan-ip3b | ok lets do this!!\nso we are given a linked list and an number \'n\'\nthis n is the number of root from last which needs to be removed!!\nfor example\n1->2->3-> | naturally_aspirated | NORMAL | 2020-04-20T17:58:08.732986+00:00 | 2020-04-20T17:59:54.525477+00:00 | 10,743 | false | ok lets do this!!\nso we are given a linked list and an number \'n\'\nthis n is the number of root from last which needs to be removed!!\nfor example\n1->2->3->4->5->6->7\nn=3\nmeans we have to delete the 3rd node from the last(5th node from the beginning).\nnow that the question is clear !\n\nlets move to the answer!\npiece of advice-whenever you see a linked list removal type question ,always make a dummy node at the beginning!\nanyways!\n\nLOGIC-\n1>we keep two pointer slow and fast(both move one at a time)both initially at start of list(at the dummy node)\n2>we move the fast to n+1 places away from the slow pointer\n3>we then traverse the list we check if fast is equal to null or not,if it is null we know that the slow pointer has reached just one node before the node we need to delete!\n4>then we slow.next=slow.next.next!\n\nshould we do a dry run!\nwhy not!\nsuppose:\n1->2->3->4->5->6\nn=2\nmake a dummy node with val=0;(we call this start)\nso now our list looks like\n0->1->2->3->4->5->6\nslow ,start , fast all are pointing to 0 valued node!\nafter executing step 2 of our algorithm we have \nslow and start still at 0\nbut fast is at node with val 3;\nnow we execute step 3\ndifferent positions of slow and fast is shown below!\n[slow=1,fast=4]->[slow=2,fast=5]->[slow=3,fast=6]->[slow=4,fast=null]\nwow!!slow have reached one node before out target node\nnow just do slow.next=slow.next.next;\n\ndo a couple of dry runs on your own to get the logic!\n```\npublic ListNode removeNthFromEnd(ListNode head, int n) {\n \n ListNode start = new ListNode(0);\n ListNode slow = start, fast = start;\n start.next = head;\n \n \n for(int i=1; i<=n+1; i++) {\n fast = fast.next;\n }\n \n while(fast != null) {\n slow = slow.next;\n fast = fast.next;\n }\n\n slow.next = slow.next.next;\n return start.next;\n}\n```\n\nhope it helps!\nupvote the answer if you like it so that more people can benefit !\n | 150 | 2 | ['Java'] | 15 |
remove-nth-node-from-end-of-list | C++ || del. n-th node from the end. | c-del-n-th-node-from-the-end-by-m_isha_1-wajw | 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 | m_isha_125 | NORMAL | 2022-10-29T18:30:34.285567+00:00 | 2022-10-29T18:30:34.285599+00:00 | 15,951 | 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: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```\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* removeNthFromEnd(ListNode* head, int n) {\n ListNode* temp=new ListNode();\n temp->next=head;\n\n ListNode* fast=temp;\n ListNode* slow=temp;\n\n for(int i=1;i<=n;i++){\n fast=fast->next;\n }\n\n while(fast->next!=NULL){\n fast=fast->next;\n slow=slow->next;\n }\n\n ListNode* gaya=slow->next;\n slow->next=slow->next->next;\n delete(gaya);\n \n return temp->next;\n }\n};\nif it helps plzz don\'t Forget to upvote it :)\n``` | 130 | 0 | ['Linked List', 'C++'] | 9 |
remove-nth-node-from-end-of-list | Beats 100% || Full proper explanation with images | beats-100-full-proper-explanation-with-i-w5ez | Intuition\nwe can find the nth node just by one traversal by using two pointer approach.\n Describe your first thoughts on how to solve this problem. \n\n# Appr | raunakkodwani | NORMAL | 2023-05-06T11:09:01.550967+00:00 | 2023-07-18T13:03:16.745368+00:00 | 25,636 | false | # Intuition\nwe can find the nth node just by one traversal by using two pointer approach.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTake two dummy nodes, who\u2019s next will be pointing to the head.\nTake another node to store the head, initially,s a dummy node(start), and the next node will be pointing to the head. The reason why we are using this extra dummy node is that there is an edge case. If the node is equal to the length of the LinkedList, then this slow will point to slow\u2019s next\u2192 next. And we can say our dummy start node will be broken and will be connected to the slow next\u2192 next.\n\nStart traversing until the fast pointer reaches the nth node.\n\n\nNow start traversing by one step both of the pointers until the fast pointers reach the end.\n \n\n\nWhen the traversal is done, just do the deleting part. Make slow pointers next to the next of the slow pointer to ignore/disconnect the given node.\n\n\n\nLast, return to the next start.\nDry Run: We will be taking the first example for the dry run, so, the LinkedList is [1,2,3,4,5] and the node which has to be deleted is 2 from the last. For the first time, fast ptr starts traversing from node 1 and reaches 2, as it traverses for node number 2, then the slow ptr starts increasing one, and as well as the fast ptr until it reaches the end.\n\n1st traversal : fast=3, slow=1\n2nd traversal : fast=4, slow=2\n3rd traversal : fast=5, slow=3\nNow, the slow->next->next will be pointed to the slow->next\n\nSo , the new linked list will be [1,2,3,5]\n\nNote that the above approach is provided by Striver on Youtube I highly recommend to checkout his video solutions.\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```\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 ListNode removeNthFromEnd(ListNode head, int n) {\n ListNode start = new ListNode();\n start.next = head;\n ListNode fast = start;\n ListNode slow = start; \n\n for(int i = 1; i <= n; ++i)\n fast = fast.next;\n \n while(fast.next != null)\n {\n fast = fast.next;\n slow = slow.next;\n }\n \n slow.next = slow.next.next;\n \n return start.next;\n }\n}\n```\n\n | 123 | 0 | ['Two Pointers', 'Java'] | 14 |
remove-nth-node-from-end-of-list | 🔥✅✅ Beats 100% with Proof | Very Easy to Understand ✅✅🔥 | beats-100-with-proof-very-easy-to-unders-c7xy | Proof - Upvote if you watching the proof\n\n\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nGiven the head of a linked list, remo | areetrahalder | NORMAL | 2024-03-03T02:07:17.652603+00:00 | 2024-03-03T02:07:17.652631+00:00 | 19,553 | false | # Proof - Upvote if you watching the proof\n\n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGiven the head of a linked list, remove the nth node from the end of the list and return its head.\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1) Calculate the size of the Single Linked List. We need to travel to the prev node of the node to be removed thus we perform reduce size by n\n2) If the node to be removed is the first node (size == 0) then we can simply return the next node of head since it will be null if the list has only one node.\n3) Traverse till the prev node using a loop again\n4) Skip the next node by linking the prev node to the next of next node. If not present, assign null. \n5. Finally return the head. \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 []\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 ListNode removeNthFromEnd(ListNode head, int n) {\n int length = findLength(head);\n int i = 0, traverseTill = length - n - 1;\n if(traverseTill == -1) return head.next;\n ListNode curr = head;\n while(i < traverseTill){\n curr = curr.next;\n i++;\n }\n curr.next = curr.next.next;\n return head;\n }\n public int findLength(ListNode head){\n int count = 0;\n if(head == null) return count;\n ListNode curr = head;\n while(curr != null){\n count++;\n curr = curr.next;\n }\n return count;\n }\n}\n```\n```C []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * struct ListNode *next;\n * };\n */\nstruct ListNode* removeNthFromEnd(struct ListNode* head, int n) {\n int length = 0;\n struct ListNode* curr = head;\n \n // Calculate the length of the linked list\n while (curr != NULL) {\n length++;\n curr = curr->next;\n }\n\n // Find the position to remove\n int traverseTill = length - n - 1;\n int i = 0;\n curr = head;\n\n // If the head needs to be removed\n if (traverseTill == -1) {\n head = head->next;\n free(curr);\n return head;\n }\n\n // Traverse to the node before the one to be removed\n while (i < traverseTill) {\n curr = curr->next;\n i++;\n }\n\n // Remove the nth node from the end\n struct ListNode* temp = curr->next;\n curr->next = curr->next->next;\n free(temp);\n\n return head;\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 */\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n int length = 0;\n ListNode* curr = head;\n \n // Calculate the length of the linked list\n while (curr != nullptr) {\n length++;\n curr = curr->next;\n }\n\n // Find the position to remove\n int traverseTill = length - n - 1;\n int i = 0;\n curr = head;\n\n // If the head needs to be removed\n if (traverseTill == -1) {\n head = head->next;\n delete curr;\n return head;\n }\n\n // Traverse to the node before the one to be removed\n while (i < traverseTill) {\n curr = curr->next;\n i++;\n }\n\n // Remove the nth node from the end\n ListNode* temp = curr->next;\n curr->next = curr->next->next;\n delete temp;\n\n return head;\n }\n};\n\n```\n```C# []\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * public int val;\n * public ListNode next;\n * public ListNode(int val=0, ListNode next=null) {\n * this.val = val;\n * this.next = next;\n * }\n * }\n */\npublic class Solution {\n public ListNode RemoveNthFromEnd(ListNode head, int n) {\n int length = 0;\n ListNode curr = head;\n \n // Find the length of the linked list\n while (curr != null) {\n length++;\n curr = curr.next;\n }\n \n int traverseTill = length - n - 1;\n curr = head;\n \n // Traverse to the node before the one to be removed\n for (int i = 0; i < traverseTill; i++) {\n curr = curr.next;\n }\n \n // Remove the nth node from the end\n if (traverseTill == -1) {\n return head.next;\n } else {\n curr.next = curr.next.next;\n return head;\n }\n }\n}\n\n```\n\n```Python []\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 removeNthFromEnd(self, head, n):\n length = self.findLength(head)\n i, traverseTill = 0, length - n - 1\n if traverseTill == -1:\n return head.next\n curr = head\n while i < traverseTill:\n curr = curr.next\n i += 1\n curr.next = curr.next.next\n return head\n\n def findLength(self, head):\n count = 0\n if head is None:\n return count\n curr = head\n while curr is not None:\n count += 1\n curr = curr.next\n return count\n\n```\n```Python3 []\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 removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n length = self.findLength(head)\n i, traverseTill = 0, length - n - 1\n if traverseTill == -1:\n return head.next\n curr = head\n while i < traverseTill:\n curr = curr.next\n i += 1\n curr.next = curr.next.next\n return head\n\n def findLength(self, head):\n count = 0\n if head is None:\n return count\n curr = head\n while curr is not None:\n count += 1\n curr = curr.next\n return count\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 * @param {number} n\n * @return {ListNode}\n */\nvar removeNthFromEnd = function (head, n) {\n let length = findLength(head);\n let i = 0,\n traverseTill = length - n - 1;\n if (traverseTill === -1) return head.next;\n let curr = head;\n while (i < traverseTill) {\n curr = curr.next;\n i++;\n }\n curr.next = curr.next.next;\n return head;\n\n function findLength(head) {\n let count = 0;\n if (head === null) return count;\n let curr = head;\n while (curr !== null) {\n count++;\n curr = curr.next;\n }\n return count;\n }\n};\n\n```\n```Typescript []\n/**\n * Definition for singly-linked list.\n * class ListNode {\n * val: number\n * next: ListNode | null\n * constructor(val?: number, next?: ListNode | null) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n * }\n */\n\nfunction removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {\n let length = findLength(head);\n let i = 0,\n traverseTill = length - n - 1;\n if (traverseTill === -1) return head.next;\n let curr = head;\n while (i < traverseTill) {\n curr = curr.next;\n i++;\n }\n curr.next = curr.next.next;\n return head;\n\n function findLength(head: ListNode | null): number {\n let count = 0;\n if (head === null) return count;\n let curr = head;\n while (curr !== null) {\n count++;\n curr = curr.next;\n }\n return count;\n }\n}\n\n```\n# Upvote\n\n\n | 104 | 2 | ['Linked List', 'Two Pointers', 'C', 'Python', 'C++', 'Java', 'TypeScript', 'Python3', 'JavaScript', 'C#'] | 10 |
remove-nth-node-from-end-of-list | My one pass solution | my-one-pass-solution-by-xiangyucao-c3mr | public ListNode RemoveNthFromEnd(ListNode head, int n) {\n ListNode h1=head, h2=head;\n while(n-->0) h2=h2.next;\n if(h2==null)return head. | xiangyucao | NORMAL | 2015-08-05T18:24:58+00:00 | 2018-09-13T18:08:49.746089+00:00 | 28,443 | false | public ListNode RemoveNthFromEnd(ListNode head, int n) {\n ListNode h1=head, h2=head;\n while(n-->0) h2=h2.next;\n if(h2==null)return head.next; // The head need to be removed, do it.\n h2=h2.next;\n \n while(h2!=null){\n h1=h1.next;\n h2=h2.next;\n }\n h1.next=h1.next.next; // the one after the h1 need to be removed\n return head;\n } | 94 | 5 | [] | 10 |
remove-nth-node-from-end-of-list | Python concise one-pass solution with dummy head. | python-concise-one-pass-solution-with-du-fnws | \n def removeNthFromEnd(self, head, n):\n fast = slow = dummy = ListNode(0)\n dummy.next = head\n for _ in xrange(n):\n fast | oldcodingfarmer | NORMAL | 2015-08-25T15:53:51+00:00 | 2022-02-19T07:37:53.506507+00:00 | 16,784 | false | \n def removeNthFromEnd(self, head, n):\n fast = slow = dummy = ListNode(0)\n dummy.next = head\n for _ in xrange(n):\n fast = fast.next\n while fast and fast.next:\n fast = fast.next\n slow = slow.next\n slow.next = slow.next.next\n return dummy.next | 71 | 1 | ['Two Pointers', 'Python'] | 16 |
remove-nth-node-from-end-of-list | Fast & slow pointers Care with memory leaks|0ms beats 100% | fast-slow-pointers-care-with-memory-leak-3ofe | Intuition\n Describe your first thoughts on how to solve this problem. \nThe fast pointer is n steps away from the slow.\n# Approach\n Describe your approach to | anwendeng | NORMAL | 2024-03-03T00:11:22.174597+00:00 | 2024-03-03T04:52:35.224248+00:00 | 7,553 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe fast pointer is n steps away from the slow.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n[Please turn on English subtitles if necesssary]\n[https://youtu.be/OqLR3ShDALY?si=Pz17e_fjYog6zCDr](https://youtu.be/OqLR3ShDALY?si=Pz17e_fjYog6zCDr)\n1. Let fast go n moves\n2. Move slow & fast step by step until fast goes to the end\n3. Remove the nth node from the end\n\nThe code is done several months ago, C, C++ codes without memory leaks are made.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(|*head|)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Code\n```Python3 []\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 removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n fast=head\n slow=head\n for _ in range(n):\n fast=fast.next\n if not fast: return head.next\n while fast.next:\n fast=fast.next\n slow=slow.next\n slow.next=slow.next.next\n return head\n \n```\n\n```C++ []\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 ListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode* fast = head;\n ListNode* slow = head;\n \n // Move the fast pointer n positions ahead\n for (int i = 0; i < n; i++) {\n fast = fast->next;\n }\n \n // Handle the case when the first element is to be removed\n if (fast == NULL) {\n return head->next;\n }\n \n // Move both pointers until the fast pointer reaches the end\n while (fast->next) {\n fast = fast->next;\n slow = slow->next;\n }\n \n // Remove the nth node from the end\n slow->next = slow->next->next;\n \n return head;\n }\n};\n\n```\n# C, C++ code without memory leaks||C 0ms beats 100%\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")\nstruct ListNode* removeNthFromEnd(struct ListNode* head, int n) {\n struct ListNode* fast=head, *slow=head;\n for(register i=0; i<n; i++) fast=fast->next;\n if (!fast) {\n struct ListNode* newHead=head->next;\n free(head); //avoid of memory leaks\n return newHead;\n }\n while(fast->next){\n fast=fast->next, slow=slow->next;\n }\n struct ListNode *node= slow->next;\n slow->next = slow->next->next;\n free(node);//avoid of memory leaks\n return head;\n}\n```\n\n```C++ []\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode* fast = head;\n ListNode* slow = head;\n \n // Move the fast pointer n positions ahead\n for (int i = 0; i < n; i++) {\n fast = fast->next;\n }\n \n // Handle the case when the first element is to be removed\n if (fast == NULL) {\n ListNode* newHead=head->next;\n delete head; //avoid of memory leaks\n return newHead;\n }\n \n // Move both pointers until the fast pointer reaches the end\n while (fast->next) {\n fast = fast->next;\n slow = slow->next;\n }\n \n // Remove the nth node from the end\n ListNode *node= slow->next;\n slow->next = slow->next->next;\n delete node;//avoid of memory leaks\n \n return head;\n }\n};\n\n``` | 52 | 1 | ['Linked List', 'Two Pointers', 'C', 'C++', 'Python3'] | 11 |
remove-nth-node-from-end-of-list | Single pass python solution | O(N) | Easy | SR | single-pass-python-solution-on-easy-sr-b-596c | Please upvote if you get this\n\nclass Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n i,j=head, hea | sathwickreddy | NORMAL | 2021-08-13T13:23:32.618241+00:00 | 2021-08-13T13:23:32.618272+00:00 | 5,677 | false | **Please upvote if you get this**\n```\nclass Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n i,j=head, head\n for k in range(n):\n j = j.next\n #now i and j will be at difference n\n if j == None: #Only happens when we are supposed to remove the first element\n return head.next\n while j.next != None:\n i = i.next\n j = j.next\n i.next = i.next.next\n return head\n\n``` | 51 | 1 | ['Linked List', 'Two Pointers', 'Python', 'Python3'] | 6 |
remove-nth-node-from-end-of-list | C++ | Diagram | Related Problems | c-diagram-related-problems-by-kiranpalsi-q8q6 | Approach\n- Take two pointers p and q at the head of linked list.\n- Move q pointers by n to the right. Here n = 2.\n- Then move both p and q pointers to right | kiranpalsingh1806 | NORMAL | 2022-09-28T02:31:50.436903+00:00 | 2022-09-28T02:31:50.436944+00:00 | 4,596 | false | **Approach**\n- Take two pointers p and q at the head of linked list.\n- Move q pointers by n to the right. Here n = 2.\n- Then move both p and q pointers to right until q reaches the end.\n- Then change pointer of p node to its next to next node.\n- Don\'t forget to delete the last nth node.\n\n**Digram Representation**\n\n\n\n**C++ Code**\n\n```cpp\nListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode *p = head, *q = head;\n while (n--) q = q->next;\n if (!q) return head->next;\n while (q->next) {\n p = p->next;\n q = q->next;\n }\n ListNode* toDelete = p->next;\n p->next = p->next->next;\n delete toDelete;\n return head;\n}\n```\n\n**Related Problems**\n[1. Linked List Cycle ](https://leetcode.com/problems/linked-list-cycle/)\n[2. Linked List Cycle II ](https://leetcode.com/problems/linked-list-cycle-ii/)\n[3. Reorder List ](https://leetcode.com/problems/reorder-list/)\n[4. Sort List ](https://leetcode.com/problems/sort-list/)\n[5. Swapping Nodes in a Linked List ](https://leetcode.com/problems/swapping-nodes-in-a-linked-list/) | 48 | 0 | ['Linked List', 'Two Pointers', 'C', 'C++'] | 5 |
remove-nth-node-from-end-of-list | A simple 2ms C solution | a-simple-2ms-c-solution-by-leehomjan-qxua | struct ListNode removeNthFromEnd(struct ListNode head, int n) {\n\n struct ListNode front = head;\n struct ListNode behind = head;\n \n while (front | leehomjan | NORMAL | 2015-03-15T12:24:54+00:00 | 2018-10-14T14:58:58.962483+00:00 | 7,959 | false | struct ListNode *removeNthFromEnd(struct ListNode *head, int n) {\n\n struct ListNode* front = head;\n struct ListNode* behind = head;\n \n while (front != NULL) {\n front = front->next;\n \n if (n-- < 0) behind = behind->next;\n }\n if (n == 0) head = head->next;\n else behind->next = behind->next->next;\n return head;\n} | 46 | 3 | [] | 8 |
remove-nth-node-from-end-of-list | Java solution 1ms \u5bb9\u6613\u7406\u89e3 | java-solution-1ms-u5bb9u6613u7406u89e3-b-znam | //\u8fd8\u662f\u8d70\u7684\u5feb\u7684\u70b9(fastNode)\u4e0e\u8d70\u5f97\u6162\u7684\u70b9(slowNode)\u8def\u7a0b\u5dee\u7684\u95ee\u9898\n \tpublic static Li | mrzenz | NORMAL | 2016-04-11T09:00:36+00:00 | 2018-10-11T03:04:24.106830+00:00 | 14,488 | false | //\u8fd8\u662f\u8d70\u7684\u5feb\u7684\u70b9(fastNode)\u4e0e\u8d70\u5f97\u6162\u7684\u70b9(slowNode)\u8def\u7a0b\u5dee\u7684\u95ee\u9898\n \tpublic static ListNode removeNthFromEnd(ListNode head, int n) {\n ListNode headNode = new ListNode(9527);\n headNode.next = head;\n ListNode fastNode = headNode;\n ListNode slowNode = headNode;\n while(fastNode.next != null){\n \tif(n <= 0)\n \t\tslowNode = slowNode.next;\n \tfastNode = fastNode.next;\n \tn--;\n }\n if(slowNode.next != null)\n \tslowNode.next = slowNode.next.next;\n return headNode.next;\n } | 43 | 3 | [] | 17 |
remove-nth-node-from-end-of-list | 100 % Faster🔥🔥 JAVA CODE || YOU WILL NOT GET THIS MUCH EASY CODE😎✌️ | 100-faster-java-code-you-will-not-get-th-2tmw | 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-17T12:31:19.232782+00:00 | 2023-03-17T12:32:10.871587+00:00 | 6,260 | 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 ListNode removeNthFromEnd(ListNode head, int n) {\n\n // Create a temporary node and a counter to find the length of the linked list\n ListNode temp = head;\n int count = 0;\n\n // Traverse the linked list and count the number of nodes\n while (temp != null) {\n count++;\n temp = temp.next;\n }\n\n // Calculate the index of the node to be removed from the beginning of the list\n int len = count - n;\n\n // If the first node needs to be removed, update the head and return\n if (len == 0) {\n head = head.next;\n } \n else {\n // Traverse the list until the node before the one to be removed\n ListNode prev = head;\n while (len - 1 != 0) {\n prev = prev.next;\n len--;\n }\n // Remove the node by updating the previous node\'s next pointer\n prev.next = prev.next.next;\n }\n\n // Return the head node of the modified list\n return head;\n }\n}\n``` | 38 | 0 | ['Linked List', 'Java'] | 1 |
remove-nth-node-from-end-of-list | Python Solution using Two Pointers | python-solution-using-two-pointers-by-wt-1188 | \nclass Solution(object):\n def removeNthFromEnd(self, head, n):\n\t\n slow = head # finally point to the previous node of the target node\n fa | wty980711 | NORMAL | 2020-02-16T03:12:06.946462+00:00 | 2020-02-16T03:12:06.946507+00:00 | 4,418 | false | ```\nclass Solution(object):\n def removeNthFromEnd(self, head, n):\n\t\n slow = head # finally point to the previous node of the target node\n fast = head # finally point to the last node\n for i in range(n): # let the fast pointer move n steps ahead of the slow pointer\n fast = fast.next\n \n # This situation would happen when we are required to del the first node (n = len(List))\n # Also, it can handle the [] case\n if not fast:\n return slow.next\n \n while fast.next:\n fast = fast.next\n slow = slow.next\n \n slow.next = slow.next.next\n return head\n``` | 37 | 2 | ['Python'] | 7 |
remove-nth-node-from-end-of-list | Easy Beginner Friendly 🔥|| Beats 100% || Notes++ || Java, C++, Python | easy-beginner-friendly-beats-100-notes-j-30is | Intuition & ApproachComplexityCode | VIBHU_DIXIT | NORMAL | 2025-03-13T05:42:05.350082+00:00 | 2025-03-13T05:42:05.350082+00:00 | 4,004 | false | # Intuition & Approach

# Complexity

# Code
```java []
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode res = new ListNode(0, head);
ListNode dummy = res;
for(int i=0;i<n;i++) head = head.next;
while(head!=null){
head = head.next;
dummy = dummy.next;
}
dummy.next = dummy.next.next;
return res.next;
}
}
```
```c++ []
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
// Create a dummy node to handle edge cases
ListNode* res = new ListNode(0, head);
ListNode* dummy = res;
// Move the head pointer n steps forward
for (int i = 0; i < n; i++) {
head = head->next;
}
// Move both pointers until head reaches the end
while (head != nullptr) {
head = head->next;
dummy = dummy->next;
}
// Remove the nth node from the end
dummy->next = dummy->next->next;
// Return the updated list
return res->next;
}
};
```
```python []
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# Create a dummy node to handle edge cases
res = ListNode(0, head)
dummy = res
# Move the head pointer n steps forward
for _ in range(n):
head = head.next
# Move both pointers until head reaches the end
while head:
head = head.next
dummy = dummy.next
# Remove the nth node from the end
dummy.next = dummy.next.next
# Return the updated list
return res.next
```
 | 36 | 3 | ['Linked List', 'Two Pointers', 'Python', 'C++', 'Java'] | 0 |
remove-nth-node-from-end-of-list | Python/Go/JS/C++ O(n) by two-pointers [w/ Visualization] | pythongojsc-on-by-two-pointers-w-visuali-sm6l | O(n) one-pass by two-pointers and delay\n\n---\n\nHint:\n\nThink of two-pointers with n-step delay.\n\nFirst pointer keeps going till the end.\nSecond pointer t | brianchiang_tw | NORMAL | 2020-05-04T07:08:23.025106+00:00 | 2022-09-29T09:23:50.775636+00:00 | 5,035 | false | O(n) one-pass by two-pointers and delay\n\n---\n\n**Hint**:\n\nThink of **two-pointers** with **n-step delay**.\n\nFirst pointer keeps going till the end.\nSecond pointer traverses to the previous node of the one being removed with n-step delay.\n\nWhen first pointer reach the end, the second one will be on the right position.\nThen update linkage of second pointer and remove the N-th node from the end.\n\n---\n\n**Visualization & Diagram**:\n\n\n\n---\n\n\n\n---\n\n\n\n---\n\n\n\n---\n\n**Implementation** by two-pointers and delay in Python:\n\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\n\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n \n # use dummy head will make the removal of head node easier\n dummy_head = ListNode(-1)\n dummy_head.next = head\n \n # cur keeps iteration till the end\n # prev_of_removal traverses to the previous node of the one of being removed\n cur, prev_of_removal = dummy_head, dummy_head\n \n \n while cur.next != None:\n \n # n-step delay for prev_of_removal\n if n <= 0:\n prev_of_removal = prev_of_removal.next\n \n cur = cur.next\n \n n -=1\n \n \n # Remove the N-th node from end of list\n n_th_node = prev_of_removal.next\n prev_of_removal.next = n_th_node.next\n \n del n_th_node\n \n return dummy_head.next\n```\n\n---\n\nJavascript:\n\n```\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 * @param {number} n\n * @return {ListNode}\n */\nvar removeNthFromEnd = function(head, n) {\n \n // use dummy head will make the removal of head node easier\n let dummyHead = new ListNode( -1, head);\n \n // cur keeps iteration till the end\n // prev_of_removal traverses to the previous node of the one of being removed \n let cur = dummyHead;\n let prevOfRemoval = dummyHead;\n \n while( cur.next != null ){\n \n // n-step delay for prevOfRemoval\n if( n <= 0 ){\n prevOfRemoval = prevOfRemoval.next;\n }\n \n cur = cur.next;\n \n // update counter of n-step delay\n n -= 1;\n }\n \n \n nThNode = prevOfRemoval.next;\n prevOfRemoval.next = nThNode.next;\n \n return dummyHead.next;\n \n};\n```\n\n---\n\n**Implementation** by two-pointers and delay in Go:\n\n```\n/**\n * Definition for singly-linked list.\n * type ListNode struct {\n * Val int\n * Next *ListNode\n * }\n */\n\nfunc removeNthFromEnd(head *ListNode, n int) *ListNode {\n \n dummyHead := &ListNode{-1, head}\n \n cur, prevOfRemoval := dummyHead, dummyHead\n \n for cur.Next != nil{\n \n // n step delay for prevOfRemoval\n if n <= 0 {\n prevOfRemoval = prevOfRemoval.Next\n }\n \n cur = cur.Next\n \n n -= 1\n }\n \n // Remove the N-th node from end of list\n nthNode := prevOfRemoval.Next\n prevOfRemoval.Next = nthNode.Next\n \n return dummyHead.Next\n \n}\n```\n\n---\n\nC++\n\n```\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n \n // use dummy head will make the removal of head node easier\n ListNode* dummyHead = new ListNode(-1, head);\n \n // cur keeps iteration till the end\n // prevOfRemoval traverses to the previous node of the one of being removied\n ListNode* cur = dummyHead;\n ListNode* prevOfRemoval = dummyHead;\n \n while( cur->next != nullptr ){\n \n // n-step delay for prevOfRemoval\n if( n <= 0 ){\n prevOfRemoval = prevOfRemoval->next;\n }\n \n cur = cur->next;\n \n // update counter of n step delay\n n -= 1;\n }\n \n // Remove the n-th node from end of list\n ListNode* nThNode = prevOfRemoval->next;\n prevOfRemoval->next = nThNode->next;\n \n delete nThNode;\n \n return dummyHead->next;\n \n \n \n }\n};\n``` | 33 | 0 | ['Two Pointers', 'C', 'Iterator', 'Python', 'Go', 'Python3', 'JavaScript'] | 5 |
remove-nth-node-from-end-of-list | ✅ [Accepted] Solution for Swift | accepted-solution-for-swift-by-asahiocea-lwob | \nDisclaimer: By using any content from this post or thread, you release the author(s) from all liability and warranty of any kind. You are free to use the cont | AsahiOcean | NORMAL | 2021-12-24T04:50:22.911477+00:00 | 2022-04-28T10:33:19.959353+00:00 | 3,454 | false | <blockquote>\n<b>Disclaimer:</b> By using any content from this post or thread, you release the author(s) from all liability and warranty of any kind. You are free to use the content freely and as you see fit. Any suggestions for improvement are welcome and greatly appreciated! Happy coding!\n</blockquote>\n\n```swift\nclass Solution {\n func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {\n let node = ListNode(0)\n node.next = head\n \n var prev: ListNode? = node\n var post: ListNode? = node\n \n for _ in 0..<n {\n guard let next = post?.next else { continue }\n post = next\n }\n \n while let postNext = post?.next, let prevNext = prev?.next {\n prev = prevNext\n post = postNext\n }\n \n prev!.next = prev!.next!.next\n \n return node.next\n }\n}\n```\n\n<hr>\n\n<p>\n<details>\n<summary><b>ListNode + Extension</b></summary>\n\n```swift\npublic 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 // An additional initializer that can be used to implement nodes from an array\n public init?(_ array: [Int]) {\n guard !array.isEmpty else { return nil }\n self.val = array[0]\n var prev: ListNode = self\n for i in 1..<array.count {\n let new = ListNode(array[i])\n prev.next = new\n prev = new\n }\n }\n}\n```\n\n```swift\nextension ListNode: Equatable {\n public static func == (lhs: ListNode, rhs: ListNode) -> Bool {\n return lhs.val == rhs.val && lhs.next == rhs.next\n }\n}\n```\n\n</details>\n</p>\n\n<hr>\n\n<p>\n<details>\n<summary><img src="https://git.io/JDblm" height="24"> <b>TEST CASES</b></summary>\n\n<br>\n\n<pre>\nResult: Executed 3 tests, with 0 failures (0 unexpected) in 0.034 (0.036) seconds\n</pre>\n\n```swift\nimport XCTest\n\nclass Tests: XCTestCase {\n \n private let solution = Solution()\n \n func test0() {\n let value = solution.removeNthFromEnd(ListNode([1,2,3,4,5]), 2)\n XCTAssertEqual(value, ListNode([1,2,3,5]))\n }\n func test1() {\n let value = solution.removeNthFromEnd(ListNode([1]), 1)\n XCTAssertEqual(value, ListNode([]))\n }\n func test2() {\n let value = solution.removeNthFromEnd(ListNode([1,2]), 1)\n XCTAssertEqual(value, ListNode([1]))\n }\n}\n\nTests.defaultTestSuite.run()\n```\n\n</details>\n</p> | 32 | 0 | ['Swift'] | 1 |
remove-nth-node-from-end-of-list | Simple and fast C++ solution with explanation | simple-and-fast-c-solution-with-explanat-3iop | \nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode* slow = head;\n ListNode* fast = head;\n \n | shlom | NORMAL | 2019-12-11T15:53:23.637801+00:00 | 2019-12-11T15:53:23.637839+00:00 | 5,298 | false | ```\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode* slow = head;\n ListNode* fast = head;\n \n\t\t// move fast pointer to the n + 1 element\n while (n--) { fast = fast->next; }\n \n // handle edge case: given n is always valid, \n // if fast reached the end, we need to remove the first element\n if (fast == nullptr) return head->next;\n\n // move both pointers at the same time maintaing the difference\n while (fast->next != nullptr) {\n fast = fast->next;\n slow = slow->next;\n }\n \n // slow will be pointing to the element before the one we want to remove\n slow->next = slow->next->next;\n \n return head;\n }\n};\n``` | 32 | 1 | ['C', 'C++'] | 2 |
remove-nth-node-from-end-of-list | Removing Nth Node from End of Linked List | | Slow-Fast Approach | | 100% beats | | 💯💯 | removing-nth-node-from-end-of-linked-lis-6wk2 | \n\n# Intuition\nTo remove the Nth node from the end of the linked list, we can first traverse the list to find its length. Then, we calculate the position of t | Hunter_0718 | NORMAL | 2024-03-03T02:34:03.060466+00:00 | 2024-03-03T06:35:51.753145+00:00 | 4,498 | false | \n\n# Intuition\nTo remove the Nth node from the end of the linked list, we can first traverse the list to find its length. Then, we calculate the position of the node to be removed from the beginning by subtracting N from the length. After that, we traverse the list again until we reach the node just before the one to be removed, update the pointers accordingly, and delete the node.\n\n# Approach\n1. Traverse the linked list to find its length.\n2. Calculate the position of the node to be removed from the beginning by subtracting N from the length.\n3. Traverse the list again until we reach the node just before the one to be removed.\n4. Update the pointers accordingly to remove the node.\n5. Delete the removed node.\n\n# Complexity\n- Time complexity: O(n), where n is the number of nodes in the linked list. We traverse the list twice.\n- Space complexity: O(1), as we are using only a constant amount of extra space.\n\n# Code\n```java []\n/*\n * Definition for singly-linked list.\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 removeNthFromEnd(ListNode head, int n) {\n int len = 0;\n ListNode temp = head;\n \n // Step 1: Traverse the linked list to find its length\n while(temp != null) {\n len++;\n temp = temp.next;\n }\n \n // Reset temp to the head of the list\n temp = head;\n ListNode prev = null;\n int pos = len - n;\n \n // Special case: If the node to be removed is the head itself\n if(pos == 0) return head.next;\n \n // Step 2: Traverse the list again to reach the node just before the one to be removed\n for(int i = 0; i < pos; i++) {\n prev = temp;\n temp = temp.next;\n }\n \n // Step 3: Update the pointers to remove the node\n prev.next = temp.next;\n \n // Step 4: Delete the removed node\n temp = null;\n \n return head;\n }\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 */\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n int len = 0;\n ListNode *temp = head;\n \n // Step 1: Traverse the linked list to find its length\n while(temp != nullptr) {\n len++;\n temp = temp->next;\n }\n \n // Reset temp to the head of the list\n temp = head;\n ListNode* prev;\n int pos = len - n;\n \n // Special case: If the node to be removed is the head itself\n if(pos == 0) return head->next;\n \n // Step 2: Traverse the list again to reach the node just before the one to be removed\n for(int i = 0; i < pos; i++) {\n prev = temp;\n temp = temp->next;\n }\n \n // Step 3: Update the pointers to remove the node\n prev->next = temp->next;\n \n // Step 4: Delete the removed node\n delete temp;\n \n return head; \n }\n};\n```\n\n# Dry Run\nLet\'s dry run the provided test case `[1,2,3,4,5]`:\n\n1. Initial State: `head` points to the first node `[1]`.\n\n2. We traverse the list to find its length. The length is 5.\n\n3. We calculate the position of the node to be removed from the beginning: `pos = 5 - 2 = 3`.\n\n4. We traverse the list again to reach the node just before the one to be removed.\n\n5. After traversal, `prev` points to node `[3]` and `temp` points to node `[4]`.\n\n6. We update the pointers to remove node `[4]` from the list.\n\n7. The list becomes `[1,2,3,5]`, and the node `[4]` is deleted.\n\n8. The final state of the list is returned.\n\n\n\n\n\n# One - Pass Solution (Slow - Fast Approach)\n\n1. **Initialization**: Initialize two pointers, `slow` and `fast`, both pointing to the head of the linked list.\n\n2. **Move `fast` pointer**: Move the `fast` pointer `n` steps ahead of the `slow` pointer. This effectively creates a gap of `n` nodes between the `slow` and `fast` pointers.\n\n3. **Handle special case**: If `fast` pointer becomes `NULL` after moving `n` steps, it means the node to be deleted is the head node. So, simply move the head to the next node and delete the original head.\n\n4. **Move both pointers until `fast` reaches the end**: Now, move both pointers (`slow` and `fast`) simultaneously until `fast` reaches the last node (`fast->next` becomes `NULL`). At this point, `slow` will be pointing to the node just before the node to be deleted.\n\n5. **Remove the node**: Once we find the node just before the one to be deleted (`slow`), we simply skip over the node to be deleted by updating `slow->next` to `slow->next->next`. We also store the node to be deleted (`delNode`) to delete it later.\n\n6. **Delete the node**: After removing the node from the linked list, we delete it from memory to avoid memory leaks.\n\n7. **Return the head**: Finally, return the head of the modified linked list.\n\n\n# **C++**\n```cpp\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode *slow = head;\n ListNode *fast = head;\n\n // Move fast pointer \'n\' steps ahead\n for(int i=0; i<n; i++){\n fast = fast->next;\n }\n\n // Handle special case: deletion of head node\n if(fast == NULL){\n ListNode *ans = head->next;\n delete(head);\n return ans;\n }\n\n // Move both pointers until fast reaches the end\n while(fast && fast->next){\n slow = slow->next;\n fast = fast->next;\n }\n\n // Remove the nth node from the end\n ListNode *delNode = slow->next;\n slow->next = slow->next->next;\n\n // Delete the node\n delete(delNode);\n\n // Return the head of modified list\n return head;\n }\n};\n```\n\n**This algorithm has a time complexity of O(L)**, where L is the length of the linked list. This is a one-pass solution, meaning it only needs to traverse the linked list once to find the node to be deleted.\n\n\n | 31 | 0 | ['Linked List', 'C++', 'Java'] | 14 |
remove-nth-node-from-end-of-list | 0ms faster than 100% | JAVA easy sol only Iteration no stacks | 0ms-faster-than-100-java-easy-sol-only-i-g7r1 | Please Upvote if it helped you.\n\n\npublic ListNode removeNthFromEnd(ListNode head, int n) {\n int count = 0; // creating a counter variable to get the | mishrasarthak44 | NORMAL | 2022-01-31T15:30:08.856276+00:00 | 2022-02-02T23:18:32.375565+00:00 | 1,664 | false | Please **Upvote** if it helped you.\n\n```\npublic ListNode removeNthFromEnd(ListNode head, int n) {\n int count = 0; // creating a counter variable to get the number of Nodes\n \n ListNode list = head; // here creating a Node that will point to the head Node, so the list is now pointing to the head Node\n \n while(list != null) { // as list is pointing to head Node and I wanna reach to the end Node, \n // I will run a loop starting from head Node until the end of the list i.e. until the list becomes null\n \n list = list.next; // this statement will make "list" point to the next Node ( like in i++, if i is 1 then it will become 2 )\n // before list ---> head..... now list ---> head.next ( for easy understanding )\n count++; // as we\'ll go forward, we\'ll keep on increasing our counter variable to know the size of the list\n }\n \n int node = count - n; // this is position of required Node from the start \n // if list.size() == 9 and we need to delete 2nd element from end\n // node = 9 (size) - 2 (end position) == 7 (position from start)\n \n if( node == 0) { // suppose in above example position from end is 9\n // means position from start ==> 9-9 = 0\n // we have to delete the first element that is head so we\'ll simply return head.next \n \n return head.next; // list that will pass the whole list except head because we wanna delete it so head.next \n // as mentioned earlier head.next will point to second Node head here\n\n }\n list = head; // now if you remember, we have iterated through this list pointer to know the size, so it will be pointing to the \n // last Node, in this statement I made sure that it again will point to the head Node ( Now you can understand why \n // we created a seperate Node "list" and not used the head Node in the argument\n \n while(node-- > 1) { // here I\'m simply running a loop till node becomes less than 1 (not 0 because we need to go the Node before the \n // Node we wanna delete ( like if we wanna delete 7th Node so we\'ll go to Node 6 ) you\'ll see why\n list = list.next; // now the list Node will point to the 6th Node if we wanna delete 7th, after this loop completes\n }\n list.next = list.next.next; // simply understand it by the notations below\n // current situation :- list ----> Node (6th)\n // list.next = 7th Node\n // list.next.next = 8th Node ( null if not present )\n // so here\'s the basic logic :- if we wanna remove 7th Node we\'ll just cut it\'s link from 6th Node \n // and we\'ll make our 8th Node as 7th by pointing 6th Node\'s next to the 8th Node so 6th ----> 8th \n \n return head; // we can\'t return "list" for reasons explained earlier beacaue currently list is pointing to 6th Node\n // and we have to return the starting Node so we\'ll return head Node\n // if you\'re wondering how? then let me make this also clear that "list" is not a copy of head, it\'s just pointing \n // to head Node, so the changes made will also reflect in the head Node\n // I hope I explained everything, so Please Upvote if you haven\'t already\n }\n``` | 31 | 1 | ['Iterator', 'Java'] | 3 |
remove-nth-node-from-end-of-list | JavaScript One Pass Two Pointer | javascript-one-pass-two-pointer-by-hon9g-dfzb | algorithm\n1. To remove n-th node from the end, send node hare as far as n.\n2. Move node curr and hare in same speed until hare gets the last node.\n3. Since c | hon9g | NORMAL | 2020-02-29T11:41:37.865048+00:00 | 2020-02-29T11:41:37.865083+00:00 | 5,808 | false | **algorithm**\n1. To remove n-th node from the end, send node `hare` as far as `n`.\n2. Move node `curr` and `hare` in same speed until `hare` gets the last node.\n3. Since `curr` and `hare` has gap as `n`, `curr` has n+1-th node from the end when `hare` has 1th node from the end. So change `curr.next` to `curr.next.next`.\n\n**edge case**\n`n = 3` `linked list = [1,2,3]`\n- When `n` is same with the length of the list. We need to remove first element, instead remove next element of `curr`.\n- In this case, you can find that `hare` would be `null`, because the last element of list points `null` such as `[1,2,3,null]`\n\n**complexity**\n- Time complexity: **O(N)**\n- Space complexity: **O(1)**\n```JavaScript\n/**\n * @param {ListNode} head\n * @param {number} n\n * @return {ListNode}\n */\nvar removeNthFromEnd = function(head, n) {\n let hare = head, curr = head;\n while (n--) {\n hare = hare.next;\n }\n while (hare && hare.next) {\n curr = curr.next;\n hare = hare.next;\n }\n if (!hare) {\n head = head.next;\n } else {\n curr.next = curr.next ? curr.next.next : null;\n }\n return head;\n};\n```\n\n | 29 | 2 | ['JavaScript'] | 5 |
remove-nth-node-from-end-of-list | Go | go-by-casd82-oupv | \nfunc removeNthFromEnd(head *ListNode, n int) *ListNode { \n dummy := &ListNode{Next: head}\n slow, fast := dummy, dummy\n \n for i := 0; i <= n | casd82 | NORMAL | 2020-04-20T06:26:41.797481+00:00 | 2020-04-20T06:26:41.797531+00:00 | 1,581 | false | ```\nfunc removeNthFromEnd(head *ListNode, n int) *ListNode { \n dummy := &ListNode{Next: head}\n slow, fast := dummy, dummy\n \n for i := 0; i <= n; i++ {\n fast = fast.Next\n }\n \n for fast != nil {\n fast = fast.Next\n slow = slow.Next\n }\n \n slow.Next = slow.Next.Next\n \n return dummy.Next\n}\n``` | 24 | 0 | ['Go'] | 2 |
remove-nth-node-from-end-of-list | Remove Nth Node From End of List | JS, Python, Java, C++ | Easy Two-Pointer Solution w/ Explanation | remove-nth-node-from-end-of-list-js-pyth-84i2 | (Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful, please upvote this post.)\n\n---\n\n#### Idea:\n | sgallivan | NORMAL | 2021-04-18T07:57:10.044715+00:00 | 2021-04-18T08:26:13.378211+00:00 | 578 | false | *(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful,* ***please upvote*** *this post.)*\n\n---\n\n#### ***Idea:***\n\nWith a singly linked list, the _only_ way to find the end of the list, and thus the **n**\'th node from the end, is to actually iterate all the way to the end. The challenge here is attemping to find the solution in only one pass. A naive approach here might be to store pointers to each node in an array, allowing us to calculate the **n**\'th from the end once we reach the end, but that would take **O(M) extra space**, where **M** is the length of the linked list.\n\nA slightly less naive approach would be to only store only the last **n+1** node pointers in the array. This could be achieved by overwriting the elements of the storage array in circlular fashion as we iterate through the list. This would lower the **space complexity** to **O(N+1)**.\n\nIn order to solve this problem in only one pass and **O(1) extra space**, however, we would need to find a way to _both_ reach the end of the list with one pointer _and also_ reach the **n**\'th node from the end simultaneously with a second pointer.\n\nTo do that, we can simply stagger our two pointers by **n** nodes by giving the first pointer (**fast**) a head start before starting the second pointer (**slow**). Doing this will cause **slow** to reach the **n**\'th node from the end at the same time that **fast** reaches the end.\n\n\n\nSince we will need access to the node _before_ the target node in order to remove the target node, we can use **fast.next == null** as our exit condition, rather than **fast == null**, so that we stop one node earlier.\n\nThis will unfortunately cause a problem when **n** is the same as the length of the list, which would make the first node the target node, and thus make it impossible to find the node _before_ the target node. If that\'s the case, however, we can just **return head.next** without needing to stitch together the two sides of the target node.\n\nOtherwise, once we succesfully find the node _before_ the target, we can then stitch it together with the node _after_ the target, and then **return head**.\n\n---\n\n#### ***Implementation:***\n\nThere are only minor differences between the code of all four languages.\n\n---\n\n#### ***Javascript Code:***\n\nThe best result for the code below is **60ms / 40.6MB** (beats 100% / 13%).\n```javascript\nvar removeNthFromEnd = function(head, n) {\n let fast = head, slow = head\n for (let i = 0; i < n; i++) fast = fast.next\n if (!fast) return head.next\n while (fast.next) fast = fast.next, slow = slow.next\n slow.next = slow.next.next\n return head\n};\n```\n\n---\n\n#### ***Python Code:***\n\nThe best result for the code below is **28ms / 13.9MB** (beats 92% / 99%).\n```python\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n fast, slow = head, head\n for _ in range(n): fast = fast.next\n if not fast: return head.next\n while fast.next: fast, slow = fast.next, slow.next\n slow.next = slow.next.next\n return head\n```\n\n---\n\n#### ***Java Code:***\n\nThe best result for the code below is **0ms / 36.5MB** (beats 100% / 97%).\n```java\nclass Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n ListNode fast = head, slow = head;\n for (int i = 0; i < n; i++) fast = fast.next;\n if (fast == null) return head.next;\n while (fast.next != null) {\n fast = fast.next;\n slow = slow.next;\n }\n slow.next = slow.next.next;\n return head;\n }\n}\n```\n\n---\n\n#### ***C++ Code:***\n\nThe best result for the code below is **0ms / 10.6MB** (beats 100% / 93%).\n```c++\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode *fast = head, *slow = head;\n for (int i = 0; i < n; i++) fast = fast->next;\n if (!fast) return head->next;\n while (fast->next) fast = fast->next, slow = slow->next;\n slow->next = slow->next->next;\n return head;\n }\n};\n``` | 23 | 6 | [] | 2 |
remove-nth-node-from-end-of-list | C++ || dear deleted node, rest in peace :) | c-dear-deleted-node-rest-in-peace-by-hed-7vz4 | Approach 1: actually delete the removed node\n\nThis solution is similar to many others, with one difference: actually delete the removed node. :)\n\ncpp\n L | heder | NORMAL | 2022-09-28T06:59:40.902006+00:00 | 2022-10-09T08:45:18.346011+00:00 | 2,010 | false | ### Approach 1: actually delete the removed node\n\nThis solution is similar to many others, with one difference: actually delete the removed node. :)\n\n```cpp\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode prehead(-1, head);\n ListNode* prev = &prehead;\n for (int i = 0; i < n; ++i) {\n head = head->next;\n }\n while (head) {\n head = head->next;\n prev = prev->next;\n }\n ListNode* rip = prev->next;\n prev->next = prev->next->next;\n // Don\'t be that person that leaks memory. :)\n delete rip;\n return prehead.next;\n }\n```\n\n_As always: Feedback, questions, and comments are welcome._\n\n**p.s. Join us on the [LeetCode The Hard Way Discord Server](https://discord.gg/Nqm4jJcyBf)!** | 22 | 0 | ['Linked List', 'Two Pointers', 'C'] | 3 |
remove-nth-node-from-end-of-list | C++ Simplest Solution | One Pass | Two Pointer Technique | c-simplest-solution-one-pass-two-pointer-1cl9 | To solve this problem in one-pass & O(n) space, we need to find a way to both reach the end of the linked list & reach the nth node from the end simultaneoulsy. | Mythri_Kaulwar | NORMAL | 2021-12-28T03:58:14.164961+00:00 | 2021-12-28T03:58:25.784945+00:00 | 2,119 | false | * To solve this problem in one-pass & O(n) space, we need to find a way to both reach the end of the linked list & reach the nth node from the end simultaneoulsy.\n* To do that, we initialize 2 pointers ```*fast``` & ```*slow``` both pointing to the head of the linked lits, the stagger the both by ```n``` nodes, so that ```fast``` is ```n``` nodes ahead of ```slow```.\n* Doing this will cause ```slow``` to reach the ```n```\'th node from the end at the same time that ```fast``` reaches the end.\n* Since we will need access to the node before the target node in order to remove the target node, we are going to loop until ```fast->next != NULL``` rather than until ```fast != null```, so that we stop one node earlier.\n* This method will be a problem when ```n``` is same as the no. of nodes in the linked list, which would make the first node the target node, and hence it\'s not possible to find the node before the target node. If that\'s the case, we can just return ```head->next```\n\n**Time Complexity :** O(N) - N = sz\n\n**Auxiliary Space :** O(1)\n\n**Code :**\n```\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode *fast = head, *slow = head;\n \n for(int i=0; i<n; i++) fast = fast->next;\n \n if(!fast) return head->next;\n \n while(fast->next) fast = fast->next, slow = slow->next;\n \n slow->next = slow->next->next;\n \n return head;\n }\n};\n```\n\n**If you like my solution & explanation, please upvote my post :)**\n | 22 | 0 | ['Two Pointers', 'C', 'C++'] | 4 |
remove-nth-node-from-end-of-list | ✅ 🔥 0 ms Runtime Beats 100% User 🔥|| Step By Steps Solution ✅ || Easy to Understand ✅🔥 || | 0-ms-runtime-beats-100-user-step-by-step-gi2l | \u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE AT THE END \u2705 :\n\n### Intuition :\nThe task is to remove the nth node from the end of a singly linked list | Letssoumen | NORMAL | 2024-11-14T17:52:12.622725+00:00 | 2024-11-14T17:52:12.622756+00:00 | 3,917 | false | \u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE AT THE END \u2705 :\n\n### Intuition :\nThe task is to remove the nth node from the end of a singly linked list in one pass. We can achieve this by maintaining a gap of `n` nodes between two pointers so that, when the first pointer reaches the end, the second pointer is right before the node we want to remove. This approach uses a dummy node to handle edge cases cleanly, such as when the head of the list needs to be removed.\n\n### Approach :\n1. **Dummy Node**: Introduce a dummy node pointing to the head of the list. This allows us to handle cases where the node to be removed is the head, as the dummy node provides a consistent "previous" node.\n2. **Two Pointers**: Use two pointers, `first` and `second`, both initially pointing to the dummy node.\n3. **Advance `first` Pointer**: Move the `first` pointer `n + 1` steps ahead of `second`. This will create a gap of `n` nodes between `first` and `second`.\n4. **Move Both Pointers**: Move both pointers one step at a time until `first` reaches the end of the list. At this point, `second` is right before the node to remove.\n5. **Remove the Target Node**: Adjust the `next` pointer of `second` to skip the target node.\n6. **Return the New Head**: Return `dummy.next` as the new head of the list.\n\n### Complexity Analysis :\n- **Time Complexity**: O(sz), where `sz` is the number of nodes in the list. We make a single pass through the list to find and remove the node.\n- **Space Complexity**: O(1), as we only use a few pointers and no additional space.\n\n### Code Implementations :\n\n#### Java Code :\n```java \nclass Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n ListNode dummy = new ListNode(0); // Dummy node to simplify edge cases\n dummy.next = head;\n \n ListNode first = dummy;\n ListNode second = dummy;\n \n // Move `first` n+1 steps ahead to create the necessary gap\n for (int i = 0; i <= n; i++) {\n first = first.next;\n }\n \n // Move both `first` and `second` until `first` reaches the end\n while (first != null) {\n first = first.next;\n second = second.next;\n }\n \n // Remove the nth node from the end\n second.next = second.next.next;\n \n return dummy.next; // Return the head of the modified list\n }\n}\n```\n\n#### C++ Code :\n```cpp\n#include <iostream>\nusing namespace std;\n\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode* dummy = new ListNode(0); // Dummy node to simplify edge cases\n dummy->next = head;\n \n ListNode* first = dummy;\n ListNode* second = dummy;\n \n // Move `first` n+1 steps ahead to create the necessary gap\n for (int i = 0; i <= n; i++) {\n first = first->next;\n }\n \n // Move both `first` and `second` until `first` reaches the end\n while (first != nullptr) {\n first = first->next;\n second = second->next;\n }\n \n // Remove the nth node from the end\n second->next = second->next->next;\n \n return dummy->next; // Return the head of the modified list\n }\n};\n```\n\n#### Python Code :\n```python\n\n\nclass Solution:\n def removeNthFromEnd(self, head, n):\n dummy = ListNode(0) # Dummy node to simplify edge cases\n dummy.next = head\n \n first = dummy\n second = dummy\n \n # Move `first` n+1 steps ahead to create the necessary gap\n for _ in range(n + 1):\n first = first.next\n \n # Move both `first` and `second` until `first` reaches the end\n while first:\n first = first.next\n second = second.next\n \n # Remove the nth node from the end\n second.next = second.next.next\n \n return dummy.next # Return the head of the modified list\n```\n\n | 21 | 1 | ['Linked List', 'Two Pointers', 'C++', 'Java', 'Python3'] | 0 |
remove-nth-node-from-end-of-list | My simple Java solution in one pass | my-simple-java-solution-in-one-pass-by-x-rvwh | public ListNode removeNthFromEnd(ListNode head, int n) {\n ListNode dummy=new ListNode(0);\n dummy.next=head;\n ListNode fast=dummy;\n | xiaoxiaoxiaov | NORMAL | 2015-04-16T09:18:09+00:00 | 2015-04-16T09:18:09+00:00 | 5,889 | false | public ListNode removeNthFromEnd(ListNode head, int n) {\n ListNode dummy=new ListNode(0);\n dummy.next=head;\n ListNode fast=dummy;\n ListNode slow=dummy;\n int temp=n;\n for(;fast.next!=null;temp--){\n if(temp<=0){ //control\n slow=slow.next;\n }\n fast=fast.next;\n }\n slow.next=slow.next.next;//delete Nth\n return dummy.next;\n } | 21 | 0 | [] | 5 |
remove-nth-node-from-end-of-list | One-pass simple C# solution w/ comments and explanation | one-pass-simple-c-solution-w-comments-an-nysc | Here\'s a one-pass solution with the following algorithm:\n1. Create a dummy node and let the 2 pointers, fast and slow point to that node. Dummy nodes make thi | minaohhh | NORMAL | 2022-08-15T08:19:14.966340+00:00 | 2022-08-15T08:19:36.539981+00:00 | 1,698 | false | Here\'s a one-pass solution with the following algorithm:\n1. Create a dummy node and let the 2 pointers, `fast` and `slow` point to that node. Dummy nodes make things easier, especially when we delete the **first node/head**.\n2. Position `fast` so that the gap between them is `n`\n3. To position `slow` just **behind/before the node-to-delete**, move both pointers until `fast.next` is `null` \n4. After the pointers are positioned where they should, delete the node by pointing `slow.next` to `slow.next.next`\n5. Return the head via `dummy.next`\n\n**Implementation**\n\n```\npublic ListNode RemoveNthFromEnd(ListNode head, int n) {\n\tListNode dummy = new(0, head); // Create a dummy node\n\tListNode slow = dummy, fast = dummy;\n\n\t// Gap of fast and slow is n\n\tfor (int i = 0; i < n; i++) {\n\t\tfast = fast.next;\n\t}\n\n\t// Move slow to the node behind the node to delete\n\twhile (fast?.next != null) {\n\t\tslow = slow.next;\n\t\tfast = fast.next;\n\t}\n\n\t\t\t// Delete the node\n\tslow.next = slow.next.next;\n\n\treturn dummy.next;\n}\n``` | 20 | 0 | ['Two Pointers', 'C#'] | 2 |
remove-nth-node-from-end-of-list | Here is my solution in C (one pass , 2 pointers) with comments | here-is-my-solution-in-c-one-pass-2-poin-icra | struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {\n struct ListNode* HEAD1;\n struct ListNode* HEAD2;\n HEAD1=head;\n HEAD2=head;\n | sanghi | NORMAL | 2015-05-26T16:54:40+00:00 | 2015-05-26T16:54:40+00:00 | 2,209 | false | struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {\n struct ListNode* HEAD1;\n struct ListNode* HEAD2;\n HEAD1=head;\n HEAD2=head;\n for(int i=0;i<n;i++) //take pointer HEAD1 n places ahead of HEAD2\n { \n HEAD1=HEAD1->next;\n if(!HEAD1) // when we have to delete the first node\n return head->next;\n } \n while(HEAD1->next) //take HEAD1 to last node so that HEAD2 is 1 behind the node we want to delete\n { \n HEAD2=HEAD2->next;\n HEAD1=HEAD1->next;\n \n }\n HEAD2->next=HEAD2->next->next; // delete the node next to HEAD2\n \n \n return head;\n \n} | 20 | 1 | [] | 1 |
remove-nth-node-from-end-of-list | JAVA SOLUTION 100% FASTER, with explanation, also asked in interviews | java-solution-100-faster-with-explanatio-ou1t | Upvote if you found this use full\n\nAlso asked in Adobe, Amazon, Arcesium, Factset, Intuit, Zoho, HCL\n\n\n// Steps-\n \n// Use a dummy variable pointing to | Nanndy7007 | NORMAL | 2022-01-22T06:18:36.401998+00:00 | 2022-01-22T06:18:36.402042+00:00 | 1,545 | false | **Upvote if you found this use full**\n\n**Also asked in Adobe, Amazon, Arcesium, Factset, Intuit, Zoho, HCL**\n\n```\n// Steps-\n \n// Use a dummy variable pointing to head\n\n// Use two pointer fast and slow pointing to dummy variable . Move first pointer for n steps\n\n// Then start moving both until first pointer reaches the last node and slow pointer reaches (size of list - n)th node.\n \n// Then delete the next node of slow and return dummy.next;\n\n\n// Concept-\n \n// When you move the fast pointer to nth node, the remaining nodes to traverse is (size_of_linked_list - n). \n// After that, when you start moving slow pointer and fast pointer by 1 node each, \n// it is guaranteed that slow pointer will cover a distance of (size_of_linked_list - n) nodes. And that\'s node we want to remove.\n\n\nclass Solution \n{\n public ListNode removeNthFromEnd(ListNode head, int n) \n {\n if(head.next==null)\n return null;\n ListNode dummy=new ListNode();\n dummy.next=head;\n ListNode slow=dummy;\n ListNode fast=dummy;\n \n for(int i=1;i<=n;i++)\n fast=fast.next;\n \n while(fast.next!=null)\n {\n fast=fast.next;\n slow=slow.next;\n }\n \n slow.next=slow.next.next;\n return dummy.next;\n }\n}\n\n```\n\n**Without using dummy node**\n\n```\nclass Solution \n{\n public ListNode removeNthFromEnd(ListNode head, int n) \n {\n if(head.next==null)\n return null;\n \n ListNode slow=head;\n ListNode fast=head;\n \n for(int i=1;i<=n;i++)\n fast=fast.next;\n \n // edge case handeled when we have to delete the 1st node i.e n=size of linked list\n \n if(fast==null)\n return head.next;\n \n while(fast!=null && fast.next!=null)\n {\n fast=fast.next;\n slow=slow.next;\n }\n \n slow.next=slow.next.next;\n return head;\n }\n}\n\n``` | 19 | 0 | ['Java'] | 4 |
remove-nth-node-from-end-of-list | Rust | 0ms Faster than 100% | Recursive solution with backtracking | No cloning | rust-0ms-faster-than-100-recursive-solut-zhb0 | I want to make a shout out to the online booklet Learn Rust With Entirely Too Many Linked Lists -- it\'s a good way to learn how to use Rust\'s built-in tools t | alex-graham | NORMAL | 2021-12-31T18:17:31.726487+00:00 | 2021-12-31T18:17:44.442363+00:00 | 1,236 | false | I want to make a shout out to the online booklet [Learn Rust With Entirely Too Many Linked Lists](https://rust-unofficial.github.io/too-many-lists/) -- it\'s a good way to learn how to use Rust\'s built-in tools to massage code to satisfy the borrow chcker. It provides a nice exlaination for using `mem::replace`, when to use it, and `Option\'s` helpful `take()` function.\n\n\n```\nimpl Solution {\n pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {\n remove_nth_from_end_recr(head, n).0\n }\n}\n \nfn remove_nth_from_end_recr(head: Option<Box<ListNode>>, n: i32) -> (Option<Box<ListNode>>, usize) {\n match head {\n None => (None, 1),\n Some(mut node) => {\n let (prev, num) = remove_nth_from_end_recr(node.next.take(), n);\n if n == num as i32 {\n (prev, num+1)\n } else {\n node.next = prev;\n (Some(node), num+1)\n }\n }\n }\n}\n```\n\n\n```\nRuntime: 0 ms, faster than 100.00% of Rust online submissions for Remove Nth Node From End of List.\nMemory Usage: 2.1 MB, less than 37.35% of Rust online submissions for Remove Nth Node From End of List.\n```\n | 19 | 0 | ['Rust'] | 9 |
remove-nth-node-from-end-of-list | ✅ Remove Nth Node From End of List | Simple One-Pass Solution w/ Explanation | remove-nth-node-from-end-of-list-simple-fd1az | This problem is very similar to the 1721. Swapping Nodes in a Linked List (which was given in March LeetCoding Challenge 2021 as well), just that we have to rem | archit91 | NORMAL | 2021-04-18T07:51:43.412057+00:00 | 2021-04-18T12:13:08.324037+00:00 | 2,616 | false | This problem is very similar to the **[1721. Swapping Nodes in a Linked List](https://leetcode.com/problems/swapping-nodes-in-a-linked-list/)** (which was given in *March LeetCoding Challenge 2021* as well), just that we have to **remove** the kth node from the end instead of swapping it.\n\n\n\n---\n\n\u2714\uFE0F ***Solution - I (One-Pointer, Two-Pass)***\n\nThis approach is very intuitive and easy to get. \n\n* We just iterate in the first-pass to find the length of the linked list - **`len`**.\n\n* In the next pass, iterate **`len - n - 1`** nodes from start and delete the next node (which would be *`nth`* node from end).\n\n---\n\n**C++**\n```\nListNode* removeNthFromEnd(ListNode* head, int n) {\n\tListNode* iter = head;\n\tint len = 0, i = 1;\n\twhile(iter) iter = iter -> next, len++; // finding the length of linked list\n\tif(len == n) return head -> next; // if head itself is to be deleted, just return head -> next\n\tfor(iter = head; i < len - n; i++) iter = iter -> next; // iterate first len-n nodes\n\titer -> next = iter -> next -> next; // remove the nth node from the end\n\treturn head;\n}\n```\n\n---\n\n**Python**\n```\ndef removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n\tptr, length = head, 0\n\twhile ptr:\n\t\tptr, length = ptr.next, length + 1\n\tif length == n : return head.next\n\tptr = head\n\tfor i in range(1, length - n):\n\t\tptr = ptr.next\n\tptr.next = ptr.next.next\n\treturn head\n```\n\n\n***Time Complexity :*** **`O(N)`**, where, `N` is the number of nodes in the given list. \n***Space Complexity :*** **`O(1)`**, since only constant space is used.\n\n---\n---\n\n\u2714\uFE0F ***Solution (Two-Pointer, One-Pass)***\n\nWe are required to remove the nth node from the end of list. For this, we need to traverse *`N - n`* nodes from the start of the list, where *`N`* is the length of linked list. We can do this in one-pass as follows -\n\n* Let\'s assign two pointers - **`fast`** and **`slow`** to head. We will first iterate for *`n`* nodes from start using the *`fast`* pointer. \n\n* Now, between the *`fast`* and *`slow`* pointers, **there is a gap of `n` nodes**. Now, just Iterate and increment both the pointers till `fast` reaches the last node. The gap between `fast` and `slow` is still of `n` nodes, meaning that **`slow` is nth node from the last node (which currently is `fast`)**.\n\n```\nFor eg. let the list be 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9, and n = 4.\n\n1. 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> null\n ^slow ^fast\n |<--gap of n nodes-->|\n \n => Now traverse till fast reaches end\n \n 2. 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> null\n ^slow ^fast\n |<--gap of n nodes-->|\n\t\t\t\t\t\t\n\'slow\' is at (n+1)th node from end.\nSo just delete nth node from end by assigning slow -> next as slow -> next -> next (which would remove nth node from end of list).\n```\n\n * Since we have to **delete the nth node from end of list** (And not nth from the last of list!), we just delete the next node to **`slow`** pointer and return the head.\n\n---\n\n**C++**\n```\nListNode* removeNthFromEnd(ListNode* head, int n) {\n\tListNode *fast = head, *slow = head;\n\twhile(n--) fast = fast -> next; // iterate first n nodes using fast\n\tif(!fast) return head -> next; // if fast is already null, it means we have to delete head itself. So, just return next of head\n\twhile(fast -> next) // iterate till fast reaches the last node of list\n\t\tfast = fast -> next, slow = slow -> next; \n\tslow -> next = slow -> next -> next; // remove the nth node from last\n\treturn head;\n}\n```\n\n---\n\n**Python**\n```\ndef removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n\tfast = slow = head\n\tfor i in range(n):\n\t\tfast = fast.next\n\tif not fast: return head.next\n\twhile fast.next:\n\t\tfast, slow = fast.next, slow.next\n\tslow.next = slow.next.next\n\treturn head\n```\n\n\n\n***Time Complexity :*** **`O(N)`**, where, `N` is the number of nodes in the given list. Although, the time complexity is same as above solution, we have reduced the constant factor in it to half.\n***Space Complexity :*** **`O(1)`**, since only constant space is used.\n\n---\n\n**Note :** The Problem only asks us to **remove the node from the linked list and not delete it**. A good question to ask in an interview for this problem would be whether we just need to remove the node from linked list or completely delete it from the memory. Since it has not been stated in this problem if the node is required somewhere else later on, its better to just remove the node from linked list as asked.\n\nIf we want to delete the node altogether, then we can just free its memory and point it to NULL before returning from the function.\n\n\n---\n---\n\n*Best Runtime -*\n\n<table><tr><td><img src=https://assets.leetcode.com/users/images/6c81d074-139d-4de5-96f5-5943f62a2cca_1618736585.2373421.png /></td></tr></table>\n\n\n---\n---\n\n\uD83D\uDCBB\uD83D\uDC31\u200D\uD83D\uDCBBIf there are any questions or mistakes in my post, please do comment below \uD83D\uDC47 \n\n---\n--- | 19 | 1 | ['C', 'Python'] | 3 |
remove-nth-node-from-end-of-list | [C++] solution with complexity analysis || two methods || two pointers | c-solution-with-complexity-analysis-two-we6zy | T = O(m) where m is number of iterations\n### S = O(1) no extra space used\n\n // approach using single pass using fast and slow pointer\n\n\tListNode* fast = | Ved_Prakash1102 | NORMAL | 2020-12-30T14:06:32.131546+00:00 | 2020-12-30T14:06:32.131585+00:00 | 2,435 | false | ### T = O(m) where m is number of iterations\n### S = O(1) no extra space used\n```\n // approach using single pass using fast and slow pointer\n\n\tListNode* fast = head;\n\tListNode* slow = head;\n\n\tfor(int i = 0; i < n; i++) {\n\t\tfast= fast->next;\n\t}\n\n\tif (fast == nullptr) return head->next;\n\n\twhile(fast->next) {\n\t\tslow = slow->next;\n\t\tfast = fast->next;\n\t}\n\n\tslow->next = slow->next->next;\n\treturn head;\n```\n\n```\n// approach using double pass\nListNode* temp = head;\nint l = 0;\nwhile(temp) {\n temp = temp->next;\n l++;\n}\n\n// corner case\nif(l == n) {\n\treturn head->next;\n}\nListNode* p = head;\nint j = 0;\nfor(int i = 0; i < l-n-1; i++) {\n\tp = p->next;\n\tj++;\n}\n\ncout << j;\nListNode* del = p->next;\np->next = del->next;\ndelete del;\nreturn head;\n```\n | 18 | 2 | ['Two Pointers', 'C', 'C++'] | 0 |
remove-nth-node-from-end-of-list | Javascript Solution | javascript-solution-by-bunnyxl-yjjk | var removeNthFromEnd = function(head, n) {\n var nullHead = new ListNode(null);\n nullHead.next = head;\n var p1 = nullHead;\n var p | bunnyxl | NORMAL | 2015-04-27T11:10:56+00:00 | 2015-04-27T11:10:56+00:00 | 5,191 | false | var removeNthFromEnd = function(head, n) {\n var nullHead = new ListNode(null);\n nullHead.next = head;\n var p1 = nullHead;\n var p2 = nullHead;\n \n for(var i = 0; i < n + 1; i++)\n p1 = p1.next;\n while(p1 !== null){\n p2 = p2.next;\n p1 = p1.next;\n }\n p2.next = p2.next.next;\n return nullHead.next;\n }; | 18 | 1 | ['JavaScript'] | 1 |
remove-nth-node-from-end-of-list | C++/Java/Python/JavaScript ||🚀 ✅ With Explanation ||🚀 ✅ Linked List | cjavapythonjavascript-with-explanation-l-0frm | Intuition:\nThe problem is to remove the nth node from the end of a linked list. We can find the total number of nodes in the linked list and then traverse the | devanshupatel | NORMAL | 2023-05-11T14:16:43.310477+00:00 | 2023-05-11T14:16:43.310516+00:00 | 8,142 | false | # Intuition:\nThe problem is to remove the nth node from the end of a linked list. We can find the total number of nodes in the linked list and then traverse the list again to find the nth node from the end. We can then remove the node by updating the pointer of the previous node.\n\n# Approach:\n\n1. Initialize a pointer to the head of the linked list and a count variable to 0.\n2. Traverse the linked list and increment the count for each node until the end of the list is reached.\n3. If the count is equal to n, remove the head node and return the next node as the new head.\n4. Otherwise, initialize the pointer to the head of the linked list again and set n to count - n - 1.\n5. Traverse the linked list again and update the pointer of the previous node to remove the nth node from the end.\n6. Return the head of the linked list.\n\n# Complexity:\n\n- Time Complexity: O(n), where n is the total number of nodes in the linked list. We need to traverse the linked list twice - once to count the total number of nodes and then to find the nth node from the end.\n\n- Space Complexity: O(1), as we are not using any extra space and only using constant space for the pointers and count variable.\n\n---\n# C++\n```\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n if(head==NULL){\n return head;\n }\n ListNode* ptr=head;\n int count = 0;\n while(ptr){\n count++;\n ptr=ptr->next;\n }\n if(count==n){\n head=head->next;\n return head;\n }\n ptr=head;\n n=count-n-1;\n count=0;\n while(ptr){\n if(count==n){\n ptr->next=ptr->next->next;\n }\n count++;\n ptr=ptr->next;\n }\n return head;\n }\n};\n```\n\n---\n# JAVA\n```\nclass Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n if (head == null) {\n return head;\n }\n \n ListNode ptr = head;\n int count = 0;\n while (ptr != null) {\n count++;\n ptr = ptr.next;\n }\n \n if (count == n) {\n head = head.next;\n return head;\n }\n \n ptr = head;\n n = count - n - 1;\n count = 0;\n while (ptr != null) {\n if (count == n) {\n ptr.next = ptr.next.next;\n }\n count++;\n ptr = ptr.next;\n }\n \n return head;\n }\n}\n\n```\n---\n# Python\n```\nclass Solution(object):\n def removeNthFromEnd(self, head, n):\n if head is None:\n return head\n \n ptr = head\n count = 0\n while ptr is not None:\n count += 1\n ptr = ptr.next\n \n if count == n:\n head = head.next\n return head\n \n ptr = head\n n = count - n - 1\n count = 0\n while ptr is not None:\n if count == n:\n ptr.next = ptr.next.next\n count += 1\n ptr = ptr.next\n \n return head\n\n```\n---\n\n# JavaScript\n```\nvar removeNthFromEnd = function(head, n) {\n if (head === null) {\n return head;\n }\n \n let ptr = head;\n let count = 0;\n while (ptr !== null) {\n count++;\n ptr = ptr.next;\n }\n \n if (count === n) {\n head = head.next;\n return head;\n }\n \n ptr = head;\n n = count - n - 1;\n count = 0;\n while (ptr !== null) {\n if (count === n) {\n ptr.next = ptr.next.next;\n }\n count++;\n ptr = ptr.next;\n }\n \n return head;\n};\n``` | 17 | 0 | ['Linked List', 'Python', 'C++', 'Java', 'JavaScript'] | 6 |
remove-nth-node-from-end-of-list | ✅ 4 simple solutions explained: Recursion, two pointers 100%, stack, two runs | 4-simple-solutions-explained-recursion-t-lzg3 | In the time complexity, I will refer to the length of the list as m and n and the index from the end.\nNote: all of the solutions are run in less than or equal | venomil | NORMAL | 2020-12-23T02:41:54.841518+00:00 | 2021-11-18T14:54:58.892598+00:00 | 1,937 | false | In the time complexity, I will refer to the length of the list as `m` and n and the index from the end.\nNote: all of the solutions are run in less than or equal to O(2 * n) but with closer look some are faster than others\n\nSolution 1:\nThis solution runs in O(m + (m - n)) time with two runs once to count length second to get to the n -1 node from the end.\nSpace O(1).\n```\nListNode *removeNthFromEnd(ListNode *head, int &n) // exection with two runs\n {\n int length = 0;\n ListNode *p = head;\n\n while (p) // find length\n {\n length++;\n p = p->next;\n }\n\n if (n == length) // check if need to remove the first node\n return head->next;\n\n length -= n;\n length--;\n\n p = head;\n while (length--) // get p the node before the n-th from the end\n p = p->next;\n p->next = p->next->next; // the move the node\n\n return head;\n }\n```\n\nSolution 2:\nThis solution runs in O(m + n) time using a stack.\nspace O(m).\n```\nListNode *removeNthFromEnd(ListNode *head, int &n) // excution using stack\n{\n\tstack<ListNode *> s;\n\tint length = 0;\n\n\tListNode *t = head;\n\twhile (t) // push all nodes\n\t{\n\t\ts.push(t);\n\t\tt = t->next;\n\t\tlength++;\n\t}\n\n\tif (length == n) // if need to remove the first node\n\t\treturn head->next;\n\n\twhile (n--) // get the n-1 node from the end\n\t\ts.pop();\n\tt = s.top();\n\tt->next = t->next->next; // remove the node\n\n\treturn head;\n}\n```\n\nSolution 3:\nThis solution runs in O(m) time using backtracking and rebuilding the list.\nSpace O(m)\n```\nListNode *removeNthFromEnd(ListNode *head, int &n)\n{\n\tif(head == NULL) // if end\n\t\treturn NULL;\n\n\thead->next = removeNthFromEnd(head->next,n);// set to the next node\n\n\tif(--n == 0) // do I need to remove this node\n\t\treturn head->next;\n\treturn head;\n}\n```\n\n\n\nSolution 4:\nThis solution runs in O(m) time with two pointers with space between them thus when the one before the end the other can remove the node.\nspace O(1).\n```\nListNode *removeNthFromEnd(ListNode *head, int &n) // execution with two pointers\n{\n\tListNode *t1 = head;\n\n\twhile (t1 && n--) // get t1 to the n+1 node thus the difference between t1 and t2 is n at all times\n\t\tt1 = t1->next;\n\n\tif (t1 == NULL) // if need to remove teh first Node\n\t\treturn head->next;\n\n\tListNode *t2 = head;\n\twhile (t1->next) // find the node before n-th from the end\n\t{\n\t\tt1 = t1->next;\n\t\tt2 = t2->next;\n\t}\n\tt2->next = t2->next->next;\n\n\treturn head;\n}\n```\nIf it helps vote up so it will reach others! | 17 | 0 | ['Two Pointers', 'Stack', 'Recursion', 'C', 'C++'] | 1 |
remove-nth-node-from-end-of-list | JavaScript | javascript-by-leichaojian-8vep | \nvar removeNthFromEnd = function(head, n) {\n let root = head;\n let clone = head;\n let len = 0;\n \n while (clone) {\n len++;\n clone = clone.next; | leichaojian | NORMAL | 2019-01-20T12:38:46.573737+00:00 | 2019-06-26T09:20:52.149410+00:00 | 4,005 | false | ```\nvar removeNthFromEnd = function(head, n) {\n let root = head;\n let clone = head;\n let len = 0;\n \n while (clone) {\n len++;\n clone = clone.next;\n }\n \n let count = len - n;\n if (count === 0) return head.next;\n while (root && count > 1) {\n root = root.next;\n count--;\n }\n\n root.next = root.next && root.next.next;\n return head;\n};\n```\n\n```\nvar removeNthFromEnd = function(head, n) {\n const help = (root, count) => {\n if (root.next) count = help(root.next, count);\n \n if (count === n) root.next = root.next.next;\n return ++count;\n }\n const count = help(head, 0);\n return count === n ? head.next : head;\n};\n```\n\n```\nvar removeNthFromEnd = function(head, n) {\n const root = new ListNode(0);\n root.next = head;\n let front = root;\n let back = root;\n while (n >= 0) {\n front = front.next;\n n--;\n }\n while (front) {\n front = front.next;\n back = back.next;\n }\n back.next = back.next.next;\n return root.next;\n};\n``` | 16 | 0 | [] | 0 |
remove-nth-node-from-end-of-list | 🌟 "Best Solution Ever! 🚀 Python, Java, C++, C, JavaScript, Go, C#, Kotlin, TypeScript, Swift 💻🌟" | best-solution-ever-python-java-c-c-javas-2kd0 | 💡 IntuitionWhen solving the problem of removing the nth node from the end of a linked list, the key idea is to use two pointers (fast and slow). By placing fast | alantomanu | NORMAL | 2025-01-10T15:33:56.105406+00:00 | 2025-01-10T15:33:56.105406+00:00 | 2,380 | false |
## **💡 Intuition**
When solving the problem of removing the nth node from the end of a linked list, the key idea is to use two pointers (`fast` and `slow`). By placing `fast` `n` steps ahead of `slow`, we ensure that when `fast` reaches the end, `slow` is positioned right before the node to remove.
---
## **🚀 Approach**
1. Initialize two pointers: `fast` and `slow`, both pointing to the head of the linked list.
2. Move the `fast` pointer `n` steps ahead.
3. If `fast` becomes `None` after the above step, it means we need to remove the head node. Return `head.next` in this case.
4. Otherwise, move both pointers one step at a time until `fast.next` becomes `None`.
5. At this point, `slow.next` points to the node that needs to be removed. Adjust the `next` pointer of `slow` to skip the node.
6. Return the modified list's head.
---
## **📊 Complexity**
- **Time Complexity**:
$$O(N)$$, where \(N\) is the length of the linked list. The list is traversed twice: once to advance the `fast` pointer and another to find the node to remove.
- **Space Complexity**:
$$O(1)$$, as we use only two pointers and no extra space.
---
## **📖 Dry Run Example**
**Input**:
`head = [1, 2, 3, 4, 5]`, `n = 2`
**Steps**:
1. Place `fast` and `slow` at the head (`1`).
2. Move `fast` two steps ahead. Now:
- `fast = 3`
- `slow = 1`
3. Move both pointers one step at a time until `fast.next = None`. Now:
- `fast = 5`
- `slow = 3`
4. Skip the node after `slow`:
- Update `slow.next = slow.next.next` to remove `4`.
5. Return the modified list: `[1, 2, 3, 5]`.
---
## **💻 Code in Multiple Languages**
### **🐍 Python**
```python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
slow = head
fast = head
for _ in range(n):
fast = fast.next
if not fast:
return head.next
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return head
```
🙌 If this helped you, please **upvote** ⬆️! 😊
---
### **☕ Java**
```java
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode slow = head, fast = head;
for (int i = 0; i < n; i++) fast = fast.next;
if (fast == null) return head.next;
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return head;
}
}
```
🙌 If this helped you, please **upvote** ⬆️! 😊
---
### **⚙️ C++**
```cpp
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* slow = head;
ListNode* fast = head;
for (int i = 0; i < n; i++) fast = fast->next;
if (!fast) return head->next;
while (fast->next) {
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return head;
}
};
```
🙌 If this helped you, please **upvote** ⬆️! 😊
---
### **💻 C**
```c
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
struct ListNode* slow = head;
struct ListNode* fast = head;
for (int i = 0; i < n; i++) fast = fast->next;
if (!fast) return head->next;
while (fast->next) {
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return head;
}
```
🙌 If this helped you, please **upvote** ⬆️! 😊
---
### **🌐 JavaScript**
```javascript
var removeNthFromEnd = function(head, n) {
let slow = head, fast = head;
for (let i = 0; i < n; i++) fast = fast.next;
if (!fast) return head.next;
while (fast.next) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return head;
};
```
🙌 If this helped you, please **upvote** ⬆️! 😊
---
### **🐹 Go**
```go
func removeNthFromEnd(head *ListNode, n int) *ListNode {
slow, fast := head, head
for i := 0; i < n; i++ {
fast = fast.Next
}
if fast == nil {
return head.Next
}
for fast.Next != nil {
fast = fast.Next
slow = slow.Next
}
slow.Next = slow.Next.Next
return head
}
```
🙌 If this helped you, please **upvote** ⬆️! 😊
---
### **💼 C#**
```csharp
public class Solution {
public ListNode RemoveNthFromEnd(ListNode head, int n) {
ListNode slow = head, fast = head;
for (int i = 0; i < n; i++) fast = fast.next;
if (fast == null) return head.next;
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return head;
}
}
```
🙌 If this helped you, please **upvote** ⬆️! 😊
---
### **📱 Kotlin**
```kotlin
class Solution {
fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? {
var slow = head
var fast = head
repeat(n) { fast = fast?.next }
if (fast == null) return head?.next
while (fast?.next != null) {
fast = fast.next
slow = slow?.next
}
slow?.next = slow?.next?.next
return head
}
}
```
🙌 If this helped you, please **upvote** ⬆️! 😊
---
### **⌨️ TypeScript**
```typescript
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
let slow = head, fast = head;
for (let i = 0; i < n; i++) fast = fast.next;
if (!fast) return head.next;
while (fast.next) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return head;
}
```
🙌 If this helped you, please **upvote** ⬆️! 😊
---
### **🍎 Swift**
```swift
class Solution {
func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
var slow = head, fast = head
for _ in 0..<n { fast = fast?.next }
if fast == nil { return head?.next }
while fast?.next != nil {
fast = fast?.next
slow = slow?.next
}
slow?.next = slow?.next?.next
return head
}
}
```
🙌 If this helped you, please **upvote** ⬆️! 😊
---
| 15 | 3 | ['Linked List', 'Two Pointers', 'Swift', 'Python', 'Java', 'Go', 'TypeScript', 'Python3', 'Kotlin', 'JavaScript'] | 2 |
remove-nth-node-from-end-of-list | ✔️ 100% Fastest Swift Solution | 100-fastest-swift-solution-by-sergeylesc-o945 | \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-03-31T05:48:44.443579+00:00 | 2022-03-31T05:48:44.443619+00:00 | 995 | 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 func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {\n var fast = head\n var slow = head\n var count = n\n\n while count > 0 {\n count -= 1\n fast = fast?.next\n }\n\n if fast == nil { return head?.next }\n\n while slow != nil && fast != nil {\n if fast?.next == nil { slow?.next = slow?.next?.next } // end\n slow = slow?.next\n fast = fast?.next\n }\n\n return head\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. | 15 | 0 | ['Swift'] | 0 |
remove-nth-node-from-end-of-list | [Python] Two pointers approch, explained | python-two-pointers-approch-explained-by-kydb | Two passes solution is straightforward. For one pass solution we use the idea of 2 iterators, let one of them start at the beginning, another at index n, then w | dbabichev | NORMAL | 2021-04-18T08:49:54.674275+00:00 | 2021-04-18T08:49:54.674307+00:00 | 439 | false | Two passes solution is straightforward. For one pass solution we use the idea of `2` iterators, let one of them start at the beginning, another at index `n`, then when the second one is finished, the first one will be on the right place.\n\n#### Complexity\nTime complexity is `O(L)`, more precisely we make `2L-n` steps, where `L` is length of list, space complexity is `O(1)`. So it the end it is exactly the same as staightforward two passes solution. So, if you meet this problem in real interview, you can just explain two pass solution, and when interviewer say can you do better: explain him that another one pass solution in fact is exaclty the same time and space.\n\n#### Code\n```\nclass Solution:\n def removeNthFromEnd(self, head, n):\n dummy = ListNode(0)\n dummy.next = head\n P1, P2 = dummy, dummy\n for _ in range(n): P2 = P2.next\n \n while P2.next:\n P1 = P1.next\n P2 = P2.next\n \n P1.next = P1.next.next\n \n return dummy.next\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!** | 15 | 1 | ['Two Pointers'] | 1 |
remove-nth-node-from-end-of-list | ✅19. C++ Solution || Easy to Understand with Explanation || Conceptual & knowledgable | 19-c-solution-easy-to-understand-with-ex-inrb | Knockcat\n\n* Detailed Understanding of each Case.\n* Conceptual Approach.\n* Worth it Approach.\n* C syntax also given.\n\n\nclass Solution {\npublic:\n Lis | knockcat | NORMAL | 2022-01-18T05:22:24.087272+00:00 | 2022-01-18T05:38:17.242648+00:00 | 784 | false | **Knockcat**\n```\n* Detailed Understanding of each Case.\n* Conceptual Approach.\n* Worth it Approach.\n* C syntax also given.\n```\n```\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode *temp = new ListNode; //Allocating Memory For New Node using new Keyword;\n temp = head; //Initializing it to head;\n int cnt = 0;\n \n while(temp != NULL)\n {\n cnt++;\n temp = temp->next;\n }\n \n if(cnt == 0)\n return head;\n \n int cnt_first = (cnt - n) + 1; //position of nth node from head\n \n head = Delete(head , cnt_first , cnt); //function Delete to Delete the Node\n \n return head;\n }\n \n ListNode *Delete(ListNode *head, int pos,int cnt)\n {\n if(head == NULL)\n return head;\n \n //If Deleted Node happen to be first Node\n else if(head != NULL && pos == 1)\n {\n ListNode *curr = new ListNode; //Allocating memory using keyword new & then initializing node to head\n curr = head;\n // ListNode *curr = head; //C syntax\n head = head -> next;\n // free(curr); //C syntax\n delete curr;\n curr = NULL;\n }\n \n //If Deleted Node happen to be Last Node\n else if(head != NULL && pos == cnt ) \n {\n ListNode *curr = new ListNode; //Allocating memory using keyword new & then initializing node to head;\n curr = head;\n while (curr->next->next != NULL)\n {\n curr = curr->next;\n }\n ListNode *temp = new ListNode;\n temp = curr->next;\n // free(temp); //C syntax\n delete temp;\n temp = NULL;\n curr->next = NULL;\n }\n \n else if(cnt < pos || cnt < 1)\n {\n // cout<<"Not a valid position"<<end;\n }\n \n //If Deleted Node happen to be the Intermediate Node\n else\n {\n ListNode *curr = new ListNode; //Allocating memory using keyword new & then initializing node to head;\n curr = head;\n ListNode *prev = new ListNode;\n prev = head;\n // ListNode *prev = NULL, *curr = head; //C syntax\n while(pos > 1)\n {\n prev = curr;\n curr = curr -> next;\n pos--;\n }\n prev -> next = curr -> next;\n // free(curr); //C syntax\n delete curr;\n curr = NULL;\n }\n \n return head;\n }\n};\n``` | 14 | 0 | ['Linked List', 'C'] | 0 |
remove-nth-node-from-end-of-list | Faster than 100% C++ code ✔ | faster-than-100-c-code-by-thekalyan001-qeam | idea is to take two pointers and traverse the first pointer n nodes\ntill the time 2nd pointer will be as it is\nnow when you\'ll traverse the both poniters sim | thekalyan001 | NORMAL | 2021-11-01T09:53:51.922447+00:00 | 2022-01-06T07:20:05.669666+00:00 | 804 | false | idea is to take two pointers and traverse the first pointer n nodes\ntill the time 2nd pointer will be as it is\nnow when you\'ll traverse the both poniters simultaneously then definitely first pointer\nis gonna be at the position last and 2nd pointer will be just before the node we\'ve to delete\n\nhere first pointer is fast and 2nd pointer is slow; \nhere is the code implementation os the above approach------------------------\n```\nListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode *start=new ListNode(); \n start->next=head;\n ListNode *slow=start,*fast=start;\n for(int i=0;i<n;i++)\n fast=fast->next; //traverse n nodes\n \n while(fast->next!=nullptr){ //as i told fast will be at the last node\n fast=fast->next;\n slow=slow->next;\n }\n ListNode *del=slow->next; //step to finish matlab khatam krna hai node ko\n slow->next=slow->next->next; //next pointer of the slow will point on just after the victim node\n delete(del); //Khatam \uD83D\uDC7B\n return start->next;\n }\n```\n\nmy english ;P\n\uD83D\uDE42 why you guys always forget to upvote, it motivates me to post such answers.\n<a href="https://cutt.ly/KalyanChannel">You can checkout the Youtube channel \uD83D\uDCF1 </a> | 14 | 1 | ['C'] | 1 |
remove-nth-node-from-end-of-list | TypeScript | Memory beats 99.66% [EXPLAINED] | typescript-memory-beats-9966-explained-b-6hg8 | Intuition\nTo remove the nth node from the end of the linked list, I need to figure out how to find this node efficiently. Instead of first calculating the leng | r9n | NORMAL | 2024-09-10T22:08:33.579845+00:00 | 2024-09-10T22:08:33.579879+00:00 | 397 | false | # Intuition\nTo remove the nth node from the end of the linked list, I need to figure out how to find this node efficiently. Instead of first calculating the length of the list and then finding the node, I\u2019ll use a two-pointer technique to keep track of the node to be removed while traversing the list.\n\n# Approach\nDummy Node: Add a dummy node to simplify edge cases.\n\nTwo Pointers: Move the first pointer n+1 steps ahead. Then, move both first and second pointers together until first reaches the end.\n\nRemove Node: The second pointer will be just before the target node; adjust its next pointer to remove the target node.\n\n# Complexity\n- Time complexity:\nO(L), where L is the length of the list, since I traverse the list once.\n\n- Space complexity:\nO(1), because I only use a few extra pointers.\n\n# Code\n```typescript []\n// We assume ListNode is provided by the environment and should not be redefined.\n\nfunction removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {\n // Create a dummy node to simplify edge cases\n const dummy = new ListNode(0);\n dummy.next = head;\n let first: ListNode | null = dummy;\n let second: ListNode | null = dummy;\n\n // Move the first pointer n+1 steps ahead\n for (let i = 0; i <= n; i++) {\n first = first?.next ?? null;\n }\n\n // Move both pointers until the first pointer reaches the end\n while (first !== null) {\n first = first.next;\n second = second?.next ?? null;\n }\n\n // Remove the nth node from the end\n second!.next = second?.next?.next ?? null;\n\n // Return the new head of the list\n return dummy.next;\n}\n\n``` | 13 | 0 | ['TypeScript'] | 1 |
remove-nth-node-from-end-of-list | Java solution for beginners || LinkedList || easy-to-understand | java-solution-for-beginners-linkedlist-e-rgij | Please UPVOTE if you like my solution!\n\n\nclass Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n int count = 1;\n List | gau5tam | NORMAL | 2023-02-23T17:21:44.232698+00:00 | 2023-02-23T17:21:44.232744+00:00 | 2,720 | false | Please **UPVOTE** if you like my solution!\n\n```\nclass Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n int count = 1;\n ListNode c = head;\n while(c.next!=null){\n count++;\n c=c.next;\n }\n \n if(n == count){\n head = head.next;\n return head;\n }\n \n ListNode ln = head;\n int i= 0;\n while(++i<count-n){\n ln = ln.next; \n }\n ln.next = ln.next.next;\n \n return head;\n }\n}\n``` | 13 | 0 | ['Linked List', 'Java'] | 2 |
remove-nth-node-from-end-of-list | Python | One-pass | O(n) | Faster than 93.19% | python-one-pass-on-faster-than-9319-by-f-ostw | ```class Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n slow, fast = head, head\n \n | fourcommas | NORMAL | 2022-01-05T13:10:14.984143+00:00 | 2022-01-05T13:10:14.984183+00:00 | 2,169 | false | ```class Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n slow, fast = head, head\n \n while n > 0:\n fast = fast.next\n n -= 1\n \n while fast is not None and fast.next is not None:\n slow = slow.next\n fast = fast.next\n\n if fast is not None:\n slow.next = slow.next.next\n else:\n head = head.next\n \n return head | 13 | 0 | ['Linked List', 'Python', 'Python3'] | 5 |
remove-nth-node-from-end-of-list | My Java Solution | my-java-solution-by-violinn-f2n8 | public ListNode removeNthFromEnd(ListNode head, int n) {\n ListNode voidHead = new ListNode(-1);\n voidHead.next = head;\n ListNode p1 = vo | violinn | NORMAL | 2015-11-05T07:17:15+00:00 | 2015-11-05T07:17:15+00:00 | 3,432 | false | public ListNode removeNthFromEnd(ListNode head, int n) {\n ListNode voidHead = new ListNode(-1);\n voidHead.next = head;\n ListNode p1 = voidHead;\n ListNode p2 = voidHead;\n while (p1.next!=null){\n p1=p1.next;\n if (n--<=0)p2=p2.next;\n }\n if (p2.next!=null) p2.next=p2.next.next;\n return voidHead.next;\n } | 13 | 0 | [] | 0 |
remove-nth-node-from-end-of-list | Golang solution (3ms) | golang-solution-3ms-by-tomba-yrb9 | Example Input:\n\n| 1 | -> | 2 | -> | 3 | -> | 4 | -> | 5 |\n\nFig 1\n\n#### First Approach \n- The idea is to use two pointers left and right.\n- right will ad | tomba | NORMAL | 2017-03-11T03:36:13.685000+00:00 | 2017-03-11T03:36:13.685000+00:00 | 560 | false | Example Input:\n```\n| 1 | -> | 2 | -> | 3 | -> | 4 | -> | 5 |\n\nFig 1\n```\n#### First Approach \n- The idea is to use two pointers `left` and `right`.\n- `right` will advance `n` nodes into the list.\n- At this point `left` will point to the head of the list. (Figure 2)\n- Then, we walk `left` and `right` in tandem, until `right` reaches the end of the list.\n- At this point `left` will point to the *Nth node from the end*, which we want to remove. (Figure 3)\n```\nleft right\n| 1 | -> | 2 | -> | 3 | -> | 4 | -> | 5 |\n\nFig 2\n```\n```\n left right\n| 1 | -> | 2 | -> | 3 | -> | 4 | -> | 5 | *\n\nFig 3\n```\nThis will work. However, we have to maintain a previous pointer to `left`, in order to delete `left`. We also need to take care of the corner case where, the node to be deleted is the `head` of our list. i.e when `n` = 5 in our example.\n\nWe'll instead follow a cleaner approach which is discussed next.\n#### Second Approach\n- We employ a node called the `preHeader` node, whose `Next` pointer points to the head of our list.\n- Then we point our `left` pointer to the `preHeader` to start off with. (Figure 4)\n- The advantage of this approach is that, when our `right` pointer gets to the end of our list, `left` will be pointing to the node just before the *Nth node from the end*, which makes deleting that node very straight forward. (Figure 5/6)\n- Another advantage is that, we do not need to code anything special for handling the corner case where `n` = 5 in our example. \n```\nleft right\n| ph | -> | 1 | -> | 2 | -> | 3 | -> | 4 | -> | 5 |\n\nFig 4\n```\n```\n left right\n| ph | -> | 1 | -> | 2 | -> | 3 | -> | 4 | -> | 5 | *\n\nFig 5\n```\n```\n left right\n| ph | -> | 1 | -> | 2 | -> | 4 | -> | 5 | *\n\nFig 6\n```\n\n```c\nfunc removeNthFromEnd(head *ListNode, n int) *ListNode {\n if head == nil || n <= 0 {return head}\n preHeader := &ListNode{Next: head}\n left, right := preHeader, head\n\n for i := 0; right != nil && i < n; i++ {\n right = right.Next\n }\n for right != nil {\n left, right = left.Next, right.Next\n }\n left.Next = left.Next.Next\n return preHeader.Next\n}\n``` | 13 | 0 | [] | 1 |
remove-nth-node-from-end-of-list | 2 pointer, with original submission and thought process. Faster than 98%. | 2-pointer-with-original-submission-and-t-n8ku | So this is the original code in my submission. I\'d apparently visited this a few months back and made a hash of it, but after revisiting having learnt some bas | user2413c | NORMAL | 2020-07-06T20:14:07.458109+00:00 | 2021-01-11T18:28:18.549673+00:00 | 1,135 | false | So this is the original code in my submission. I\'d apparently visited this a few months back and made a hash of it, but after revisiting having learnt some base techniques it\'s much easier.\n\n**(1)** \nOk obviously need to delete a node. So best know how to do that. Already in my mind i\'m seeing:\n\n``` \nconst deleteNextNode = (node) => node.next = node.next.next\n```\n\nWhich means if we want to delete a node, we need to get the node before it.\n\n**(2)**\nThen the other bit, which actually comes before in the description, is to get the `Nth` node from the end. In our case, as we want to get the `Nth` node from the end of the linked list to delete it, we actually want to get the `Nth+1` node **from the end**. Seems like a slow/fast 2 pointer solution.\n\nTo do this, i\'m seeing the beginning of the answer to the entire question:\n\n```\nvar removeNthFromEnd = function(head, n) {\n\n if(!head) return head\n\n let [slow, fast] = [head, head]\n\t\n // move fast ahead by n\n\t// have to be careful about --n or n-- here. \n\t// As we want the node before the one we are deleting,\n\t// we want fast to be ahead by an additional node\n\t// if the question was just to return slow, i\'d probably use --n instead\n while(n--){\n fast = fast.next\n }\n \n\t// we want to stop when fast.next is null\n\t// we move both along the linked list \n\t// keeping the same distance between them\n while(fast.next){\n [slow, fast] = [slow.next, fast.next]\n }\n\t...\n}\n```\n\nOne final issue came up when submitting. What happens when `n` is equal to the length of the linked list. We\'ll we run into problems. Easiest solution I could think of is to create a dummy node that is before the linked list. That allows us to remove the head node if the Nth node from the end is the head node.\n\n**Final submission:**\n```\n/**\n * @param {ListNode} head\n * @param {number} n\n * @return {ListNode}\n */\nvar removeNthFromEnd = function(head, n) {\n if(!head) return head\n let begin = { val: -1, next: head }\n \n let [slow, fast] = [begin, begin]\n // move fast ahead by n\n while(n--){\n fast = fast.next\n }\n \n while(fast.next){\n [slow, fast] = [slow.next, fast.next]\n }\n \n // remove slow.next\n removeNextNode(slow)\n \n return begin.next\n};\n\nconst removeNextNode = (node) => { \n node.next = node.next.next\n}\n``` | 12 | 0 | ['Two Pointers', 'JavaScript'] | 1 |
remove-nth-node-from-end-of-list | rust safe code one pass(has to use clone to bypass borrow checker) | rust-safe-code-one-passhas-to-use-clone-boi7x | \nimpl Solution {\n pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {\n let mut dummy = ListNode::new(0);\n | leapm | NORMAL | 2019-10-27T15:11:05.256722+00:00 | 2019-10-27T15:11:05.256769+00:00 | 971 | false | ```\nimpl Solution {\n pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {\n let mut dummy = ListNode::new(0);\n dummy.next = head;\n let mut dummy = Box::new(dummy);\n let mut fast = dummy.clone();\n let mut slow = dummy.as_mut();\n // move fast n forward\n for _ in 0..n {\n fast = fast.next.unwrap();\n }\n\n while fast.next.is_some() {\n fast = fast.next.unwrap();\n slow = slow.next.as_mut().unwrap();\n }\n let next = slow.next.as_mut().unwrap();\n slow.next = next.next.clone();\n dummy.next\n }\n}\n``` | 12 | 0 | ['Rust'] | 2 |
remove-nth-node-from-end-of-list | Python3 | Beats 95% | Efficient Removal of Nth Node from the End of a Linked List | python3-beats-95-efficient-removal-of-nt-r4ql | Solution no. 01\nThe first solution helps you understand the basics with simple steps. \n\n# Intuition\n\nTo determine the node to remove, which is n positions | Samama_Jarrar | NORMAL | 2023-08-16T07:53:55.362087+00:00 | 2023-08-18T04:14:36.798868+00:00 | 1,748 | false | # Solution no. 01\nThe first solution helps you understand the basics with simple steps. \n\n# Intuition\n\nTo determine the node to remove, which is n positions from the end, we need to figure out how many positions we should move from the front to reach the desired node. By counting the total number of nodes in the linked list, we gain this insight and can then adjust the connections accordingly to remove the targeted node from the end.\n\n# Approach\n1. Count the total number of nodes in the linked list by traversing it with a curr pointer.\n1. Calculate the position to move from the front to reach the node n positions from the end.\n1. Reset the count and curr to traverse the list again.\n1. If the node to be removed is the first node, return head.next.\n1. Traverse the list while keeping track of the count.\n1. When the count matches the calculated position before the node to be removed, update the connection to skip the node.\n1. Exit the loop after performing the removal.\n1. Return the updated head.\n\n# Complexity\n- Time complexity:\nWe traverse the linked list twice, so the time complexity is O(n), where n is the number of nodes in the list.\n\n- Space complexity:\nWe only use a few variables, so the space complexity is O(1).\n\n# Code\n```\nclass Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n count = 0\n curr = head\n while curr:\n count += 1\n curr = curr.next\n\n check = count - n - 1\n count = 0\n curr = head\n\n # Removing the first node\n if check == -1: \n return head.next\n\n while curr:\n if count == check:\n curr.next = curr.next.next\n # As the removal is done, Exit the loop\n break \n curr = curr.next\n count += 1\n\n return head\n\n```\n\n\n---\n\n# Solution no. 02\n\n# Intuition\nIn our first approach we counted the total number of nodes in the linked list and then identify the n-th node from the end by its position from the beginning. While this counting approach could work, it involves traversing the list twice: once to count the nodes and once to find the node to remove. This double traversal can be inefficient, especially for large lists.\n\nA more efficient approach comes from recognizing that we don\'t really need to know the total number of nodes in the list to solve this problem. Instead, we can utilize two pointers to maintain a specific gap between them as they traverse the list. This gap will be the key to identifying the n-th node from the end.\n\n# Approach\n1. We\'ll use two pointers, first and second, initialized to a dummy node at the beginning of the linked list. The goal is to maintain a gap of n+1 nodes between the two pointers as we traverse the list.\n\n1. Move the first pointer n+1 steps ahead, creating a gap of n nodes between first and second.\n\n1. Now, move both first and second pointers one step at a time until the first pointer reaches the end of the list. This ensures that the gap between the two pointers remains constant at n nodes.\n\n1. When first reaches the end, the second pointer will be pointing to the node right before the node we want to remove (n-th node from the end).\n\n1. Update the second.next pointer to skip the n-th node, effectively removing it from the list.\n\n# Complexity\n- Time complexity:\n The solution involves a single pass through the linked list, so the time complexity is **O(N)**, where N is the number of nodes in the linked list.\n\n- Space complexity:\nWe are using a constant amount of extra space to store the dummy, first, and second pointers, so the space complexity is **O(1)**.\n\n# Code\n```\nclass Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n dummy = ListNode(0)\n dummy.next = head\n \n first = dummy\n second = dummy\n \n # Advance first pointer so that the gap between first and second is n+1 nodes apart\n for i in range(n+1):\n first = first.next\n \n # Move first to the end, maintaining the gap\n while first:\n first = first.next\n second = second.next\n \n # Remove the nth node from the end\n second.next = second.next.next\n \n return dummy.next \n\n```\n\n | 11 | 0 | ['Linked List', 'Two Pointers', 'Python', 'Python3'] | 2 |
remove-nth-node-from-end-of-list | Python3 || traverse the list and count || T/S: 83% / 99% | python3-traverse-the-list-and-count-ts-8-dwlf | \nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n \n sz, ptr = 0, head\n \n while ptr:\n | Spaulding_ | NORMAL | 2022-09-28T00:44:47.772171+00:00 | 2024-05-26T16:11:37.827672+00:00 | 1,637 | false | ```\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n \n sz, ptr = 0, head\n \n while ptr:\n ptr = ptr.next\n sz+=1\n\n if n==sz:\n return head.next\n\n sz -= n+1\n ptr = head \n \n while sz > 0:\n ptr = ptr.next\n sz-=1\n \n ptr.next = ptr.next.next \n \n return head\n\t\t\n```\t\n\n[https://leetcode.com/problems/remove-nth-node-from-end-of-list/submissions/596620800/](https://leetcode.com/problems/remove-nth-node-from-end-of-list/submissions/596620800/)\n\t\t | 11 | 0 | ['Python'] | 2 |
remove-nth-node-from-end-of-list | Simple and Easy to Understand C++ solution | simple-and-easy-to-understand-c-solution-3gtd | \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 * | himanshugupta14 | NORMAL | 2019-07-17T09:47:35.314032+00:00 | 2019-08-16T21:07:02.101535+00:00 | 494 | false | ```\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 */\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n int size=0;\n ListNode* ans=head;\n ListNode* check=head;\n while(head){\n size++;\n head=head->next;\n }\n if(size==1) return NULL;\n if(size <= n){\n return ans->next;\n }\n for(int i=1;i<size-n;i++){\n check=check->next;\n }\n check->next=check->next->next;\n return ans;\n }\n};\n``` | 11 | 0 | [] | 1 |
remove-nth-node-from-end-of-list | C++ || 0ms || Short & Simple Code || ✅⭐⭐ | c-0ms-short-simple-code-by-palashhh-vrot | DO UPVOTE IF IT HELPS !!!!\n\nLL = 1 -> 2 -> 3 -> 4-> 5 -> null & n=2\n\n1. Initially slow = head, fast = head\n2. Fast is initialised \'n+1\' positions ahead.\ | palashhh | NORMAL | 2022-09-28T03:30:57.429481+00:00 | 2022-09-28T03:31:25.528682+00:00 | 1,431 | false | ***DO UPVOTE IF IT HELPS !!!!***\n\nLL = **1 -> 2 -> 3 -> 4-> 5 -> null** & n=2\n\n1. Initially slow = head, fast = head\n2. Fast is initialised **\'n+1\' positions ahead**.\n3. Thus, **slow = 1 and fast = 4** (n+1 positions ahead i.e. 2+1 = 3 positions ahead). \n4. While fast!=NULL, increment **both slow and fast by one**.\n5. Therefore, slow = 2, fast = 5\n6. Now, slow = 3, fast = NULL, hence exit form while loop\n7. Now update **slow->next = slow->next->next.**\n\n**TC** = O(N), **SC** = O(1)\n\n\t ListNode* removeNthFromEnd(ListNode* head, int n) {\n \n if(head==NULL) return head;\n \n ListNode *s=head, *f=head; //2 pointers, slow=head\n \n for(int i=1;i<=n+1;i++){ //fast is initialised \'n+1\' positions ahead\n if(f==NULL) return head->next; \n f=f->next;\n }\n \n while(f!=NULL){ //when fast is NULL, exit\n s=s->next;\n f=f->next;\n }\n \n s->next=s->next->next; //update connection\n return head;\n } | 10 | 0 | ['Linked List', 'Two Pointers', 'C'] | 1 |
remove-nth-node-from-end-of-list | Javascript 99% Single loop clean code | javascript-99-single-loop-clean-code-by-7alpm | dummy head to keep the \'prev\' for the real head.\n2. counting in the single loop to avoid the second loop many other solutions used.\n\n\nvar removeNthFromEnd | leicaolife | NORMAL | 2021-09-19T04:28:49.799003+00:00 | 2021-09-19T04:30:16.994764+00:00 | 1,276 | false | 1. dummy head to keep the \'prev\' for the real head.\n2. counting in the single loop to avoid the second loop many other solutions used.\n\n```\nvar removeNthFromEnd = function(head, n) { \n let dummy = new ListNode(0, head);\n let prev = dummy;\n let node = head;\n let count = 1;\n while (node.next) {\n if (count === n) {\n prev = prev.next;\n } else {\n count++;\n }\n node = node.next;\n }\n prev.next = prev.next.next;\n return dummy.next;\n};\n``` | 10 | 0 | ['JavaScript'] | 3 |
remove-nth-node-from-end-of-list | Simple JavaScript 99% Solution with Comments | simple-javascript-99-solution-with-comme-wg8d | \nvar removeNthFromEnd = function(head, n) {\n let nodeToReturn = head;\n \n //Have two pointers, one that is n ahead of the other\n let pointer1 = | romner | NORMAL | 2018-09-09T14:10:04.984554+00:00 | 2018-09-18T01:35:50.902118+00:00 | 944 | false | ```\nvar removeNthFromEnd = function(head, n) {\n let nodeToReturn = head;\n \n //Have two pointers, one that is n ahead of the other\n let pointer1 = head;\n let pointer2 = head;\n \n //Move pointer2 to be n ahead\n for(let i = 0; i<n;i++){\n pointer2 = pointer2.next;\n }\n \n //If pointer2 doesn\'t exist, that means we must remove the head of the list\n if(!pointer2){\n return nodeToReturn.next;\n }\n \n //Move both pointers until pointer2 reaches the end\n while(pointer2.next){\n pointer1 = pointer1.next;\n pointer2 = pointer2.next;\n }\n\n //Save the node two places ahead of pointer1; \n pointer1.next = pointer1.next.next;\n \n return nodeToReturn;\n};\n``` | 10 | 0 | [] | 1 |
remove-nth-node-from-end-of-list | Simple one pass 4ms C++ implementation | simple-one-pass-4ms-c-implementation-by-ol546 | class Solution {\n public:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode realHead(0);\n realHead.next = head; | xuxie | NORMAL | 2015-09-03T07:09:13+00:00 | 2015-09-03T07:09:13+00:00 | 3,338 | false | class Solution {\n public:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode realHead(0);\n realHead.next = head;\n head = &realHead;\n ListNode *curr = &realHead;\n while (n-- > 0)\n curr = curr->next;\n while (curr->next != nullptr) {\n curr = curr->next;\n head = head->next;\n }\n \n head->next = head->next->next;\n return realHead.next;\n }\n }; | 10 | 1 | [] | 2 |
remove-nth-node-from-end-of-list | Python solution, one pass | python-solution-one-pass-by-hxuanz-qvb5 | nearly one pass, O(1) space. 44 ms\n\n def removeNthFromEnd(self, head, n):\n slow = fast = self\n self.next = head\n while fast.next:\n | hxuanz | NORMAL | 2016-02-02T10:09:09+00:00 | 2016-02-02T10:09:09+00:00 | 5,615 | false | nearly one pass, O(1) space. 44 ms\n\n def removeNthFromEnd(self, head, n):\n slow = fast = self\n self.next = head\n while fast.next:\n if n:\n n -= 1\n else:\n slow = slow.next\n fast = fast.next\n slow.next = slow.next.next\n return self.next \n\nreal one pass, but O(n) space, 44 ms \n\n def removeNthFromEnd(self, head, n):\n self.next, nodelist = head, [self]\n while head.next:\n if len(nodelist) == n:\n nodelist.pop(0)\n nodelist += head,\n head = head.next\n nodelist[0].next = nodelist[0].next.next \n return self.next | 10 | 0 | ['Python'] | 3 |
remove-nth-node-from-end-of-list | Easy JAVA O(1) space complexity solution | easy-java-o1-space-complexity-solution-b-ux4m | public ListNode removeNthFromEnd(ListNode head, int n) {\n\n ListNode start = new ListNode(0);\n ListNode n1 = start, n2 = start;\n n2.next | octo_cat | NORMAL | 2016-03-13T06:15:46+00:00 | 2016-03-13T06:15:46+00:00 | 2,418 | false | public ListNode removeNthFromEnd(ListNode head, int n) {\n\n ListNode start = new ListNode(0);\n ListNode n1 = start, n2 = start;\n n2.next = head;\n \n for(int i =0;i<n+1;i++){\n n2 = n2.next; // trying o create gab n between two pointers\n }\n \n while(n2 != null){\n n1 = n1.next;\n n2 = n2.next;\n }\n \n //time to change\n n1.next = n1.next.next;\n return start.next;\n } | 10 | 1 | ['Linked List', 'Two Pointers', 'Java'] | 1 |
remove-nth-node-from-end-of-list | Simple 6-line Java one-pass solution | simple-6-line-java-one-pass-solution-by-02pru | public class Solution {\n\n public ListNode removeNthFromEnd(ListNode head, int n) {\n ListNode start=new ListNode(0),slow=start,fast=start;\n | daoheng | NORMAL | 2016-03-20T22:20:32+00:00 | 2016-03-20T22:20:32+00:00 | 2,332 | false | public class Solution {\n\n public ListNode removeNthFromEnd(ListNode head, int n) {\n ListNode start=new ListNode(0),slow=start,fast=start;\n start.next=head;\n for(int i=0;i<n;i++) fast=fast.next;\n while(fast.next!=null) {fast=fast.next;slow=slow.next;}\n slow.next=slow.next.next;\n return start.next;\n }\n} | 10 | 0 | [] | 2 |
remove-nth-node-from-end-of-list | Beats 100% of users with C++ || Using Two Pointer || Step by Step Explain || Fast Solution || | beats-100-of-users-with-c-using-two-poin-ru20 | ---\n\n# Abhiraj Pratap Singh\n\n---\n\n\n# UPVOTE IT....\n\n\n---\n\n\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \n\n- The rem | abhirajpratapsingh | NORMAL | 2024-01-12T17:29:44.351234+00:00 | 2024-01-12T17:29:44.351278+00:00 | 1,204 | false | ---\n\n# Abhiraj Pratap Singh\n\n---\n\n\n# UPVOTE IT....\n\n\n---\n\n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n- The removeNthFromEnd function appears to remove the n-th node from the end of a singly-linked list.\n\n\n---\n\n\n\n\n---\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n1. Define a helper function length_ll to calculate the length of the linked list.\n2. Calculate the length of the linked list using the helper function.\n3. If the length is 1, return NULL since there is only one node, and removing it would make the list empty.\n4. If the length is equal to n, return head->next to remove the first node.\n5. Iterate through the list to reach the node before the one to be removed. Update the next pointer of this node to skip the n-th node.\n6. Return the modified head of the list.\n\n\n---\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- **Time complexity: O(n),** where n is the length of the linked list. The function iterates through the list once to calculate its length and then once more to remove the n-th node from the end.\n\n\n\n---\n\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n- **Space complexity: O(1),** The function uses a constant amount of extra space regardless of the size of the input linked list.\n\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 int length_ll(ListNode* head)\n {\n int count_node=0;\n ListNode *ptr=head;\n while(ptr!=NULL)\n {\n count_node++;\n ptr=ptr->next;\n }\n return count_node;\n }\n ListNode* removeNthFromEnd(ListNode* head, int n) \n {\n int len=length_ll(head);\n if(len==1)\n return NULL;\n if(len==n)\n return head->next;\n int node_number=0;\n ListNode *ptr=head;\n while( node_number < len-n-1 )\n {\n ptr=ptr->next;\n node_number++;\n }\n ptr->next=ptr->next->next;\n return head;\n }\n};\n```\n\n\n---\n\n---\n\n\n# if you like the solution please UPVOTE it....\n\n\n\n---\n\n\n---\n\n\n\n\n---\n--- | 9 | 0 | ['Linked List', 'Two Pointers', 'C++'] | 1 |
remove-nth-node-from-end-of-list | C++ || Easy explanation | | simple || | c-easy-explanation-simple-by-ujjwaljain1-imlv | / question me dia apko ek linked list di h or bola h Nth node from the end delete krdo mtlb agar linked list h \nL1 = [1,2,3,4,5] or N=2 to last 2nd node delet | ujjwaljain1304 | NORMAL | 2023-04-30T08:32:53.587427+00:00 | 2023-04-30T08:32:53.587469+00:00 | 2,321 | false | /* question me dia apko ek linked list di h or bola h Nth node from the end delete krdo mtlb agar linked list h \nL1 = [1,2,3,4,5] or N=2 to last 2nd node delete krdo to vo konsi hogi vo hogi vo node jiska data h 4 to hme 4 ko delete krna h iske lia hmne kya kia hmne ek fast pointer lia jo head pe khada h ek slow ha vo bhi head pe h to phle fast ko jb tk chala lo jb tk fast \'n\' nhi ho jata fir hmne kya kia ek slow pointer lia usko chlao fast ke sath jb tk fast null nhi ho jata (slow bhi ek step , fast bhi ek step) jse hi fast null ho jae to appka slow us position pe ho jisko delete krna h to abb kya kro slow ke next ko krdo slow ke next ka next */\n\n\n\n\nclass Solution {\n\npublic:\n\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n\t\n ListNode* fast = head;\n\t\t\n if(head == NULL)\n\t\t\n return NULL;\n\t\t\t\n ListNode* slow = head;\n \n int count = 1;\n while(n--){\n cout<<fast->val<<" ";\n fast = fast->next;\n }\n if(fast== NULL)\n return slow->next;\n \n while(fast->next != NULL){\n slow = slow->next;\n fast = fast->next;\n }\n slow->next = slow->next->next;\n return head;\n }\n \n}; | 9 | 0 | ['Linked List', 'Two Pointers', 'C'] | 2 |
remove-nth-node-from-end-of-list | ✅ (C++ / Python) Easy One Pass 0 ms Solution 🔥 | c-python-easy-one-pass-0-ms-solution-by-9euht | 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# C+ | gus7890 | NORMAL | 2023-03-04T20:10:36.176267+00:00 | 2023-03-06T17:23:58.290568+00:00 | 3,878 | false | # 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# C++\n```\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n vector<ListNode*> nodes;\n ListNode* temp = head;\n while (temp)\n {\n nodes.push_back(temp);\n temp = temp->next;\n }\n if (nodes.size()==1) return NULL;\n if (nodes.size()-n<=0) return nodes[1];\n ListNode* node = nodes[nodes.size()-1-n];\n node->next = node->next->next;\n return head;\n }\n};\n```\n\n# Python\n```\nclass Solution(object):\n def removeNthFromEnd(self, head, n):\n """\n :type head: ListNode\n :type n: int\n :rtype: ListNode\n """\n nodes = []\n temp = head\n while (temp):\n nodes.append(temp)\n temp = temp.next\n if (len(nodes)==1): return None\n if (len(nodes)-n<=0): return nodes[1]\n node = nodes[len(nodes)-1-n]\n node.next= node.next.next\n return head\n```\n\nUpvote if this helps please \uD83D\uDE42 | 9 | 0 | ['Array', 'Python', 'C++'] | 4 |
remove-nth-node-from-end-of-list | JAVA || 2 SOLUTIONS || EXPLAINED | java-2-solutions-explained-by-jitendrap1-vi8m | ```\n// 1. In one traversal : using slow and fast pointer\n/\ntake two pointer slow and fast\n- fast will move n position forwards\n- now move forwards slow and | jitendrap1702 | NORMAL | 2022-09-28T02:34:35.172953+00:00 | 2022-09-28T02:35:13.502767+00:00 | 1,284 | false | ```\n// 1. In one traversal : using slow and fast pointer\n/*\ntake two pointer slow and fast\n- fast will move n position forwards\n- now move forwards slow and fast both, till fast not reach to end of LL\n- after performing upper operations, slow will reach to the previous node to the node which we want to delete\n*/\nclass Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n \n ListNode slow = head, fast = head;\n \n // move fast n position forwards\n while(n != 0){\n fast = fast.next;\n n--;\n }\n \n // now move slow and fast both till fast not reach to end of LL\n while(fast != null && fast.next != null){\n fast = fast.next;\n slow = slow.next;\n }\n \n // if fast is null, its mean we want to delete head node\n if(fast == null) return head.next;\n \n // remove node\n slow.next = slow.next.next;\n \n return head;\n }\n}\n\n\n// 2. In two traversal\nclass Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n \n // find length\n int len = 0;\n ListNode temp = head;\n while(temp != null){\n temp = temp.next;\n len++;\n }\n \n if(len == n) return head.next;\n \n // Reach to the previous node of the last node\n temp = head;\n n = len-n-1;\n while(temp.next != null && n != 0){\n temp = temp.next;\n n--;\n }\n \n // remove \n if(temp.next != null)\n temp.next = temp.next.next;\n \n \n return head;\n }\n} | 9 | 0 | ['Two Pointers', 'Java'] | 0 |
remove-nth-node-from-end-of-list | Python solution | python-solution-by-shubhamyadav32100-kfx0 | \nclass Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n if head.next is None:\n return No | shubhamyadav32100 | NORMAL | 2022-09-20T00:42:51.350259+00:00 | 2022-09-20T15:10:15.861425+00:00 | 1,031 | false | ```\nclass Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n if head.next is None:\n return None\n \n size=0\n curr= head\n while curr!= None:\n curr= curr.next\n size+=1\n if n== size:\n return head.next\n \n indexToSearch= size-n\n prev= head\n i=1\n while i< indexToSearch:\n prev= prev.next\n i+=1\n prev.next= prev.next.next\n return head\n```\n\n**UPVOTE** *is the best encouragement for me... Thank you*\uD83D\uDE01 | 9 | 0 | ['Linked List', 'Python'] | 2 |
remove-nth-node-from-end-of-list | C++ || Efficient || two-pointers || with comments & explanation || | c-efficient-two-pointers-with-comments-e-vrnc | If you understand the approach please please upvote!!!\uD83D\uDC4D\nThanks :)\n\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n | Debajyoti-Shit | NORMAL | 2022-02-13T16:45:51.117468+00:00 | 2022-02-13T16:45:51.117493+00:00 | 694 | false | ##### If you understand the approach please please upvote!!!\uD83D\uDC4D\n***Thanks :)***\n```\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode *slow=head;\n ListNode *fast=head;\n while(n--) fast = fast -> next;//iterate first n nodes using fast\n\t if(!fast) return head -> next; //if fast is already null, it means we have to delete head itself. So, just return next of head\n while(fast->next){//iterate till fast reaches the last node of list\n slow=slow->next; \n fast=fast->next;\n }\n slow->next=slow->next->next;// remove the nth node from last\n return head;\n }\n};\n``` | 9 | 0 | ['Linked List', 'Two Pointers', 'C', 'C++'] | 0 |
remove-nth-node-from-end-of-list | Python 2 simple solutions | python-2-simple-solutions-by-tovam-q7oy | Python :\n\n1 :\n\n\nclass Solution:\n def getLengthOfLL(self, head: Optional[ListNode]) -> int:\n length = 0\n \n while head:\n | TovAm | NORMAL | 2021-11-06T17:26:44.241738+00:00 | 2021-11-06T17:26:44.241778+00:00 | 1,055 | false | **Python :**\n\n**1 :**\n\n```\nclass Solution:\n def getLengthOfLL(self, head: Optional[ListNode]) -> int:\n length = 0\n \n while head:\n length += 1\n head = head.next\n \n return length\n \n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n temp = head\n length = self.getLengthOfLL(temp)\n if n == length:\n return head.next\n \n if length == 1:\n return None\n \n i = 1\n \n while temp and i < (length - n):\n temp = temp.next\n i += 1\n \n temp.next = temp.next.next \n return head\n```\n\n**2 :**\n```\ndef removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n\tfast = head\n\tslow = head\n\n\twhile n:\n\t\tfast = fast.next\n\t\tn -= 1\n\n\tif not fast:\n\t\treturn head.next\n\n\twhile fast.next:\n\t\tslow = slow.next\n\t\tfast = fast.next\n\n\tslow.next = slow.next.next\n\treturn head\n```\n\n**Like it ? please upvote !**\n\n | 9 | 0 | ['Python', 'Python3'] | 2 |
remove-nth-node-from-end-of-list | C++ | One pass | 100% fast | Recursion | Solution with picture | c-one-pass-100-fast-recursion-solution-w-m50b | \n\n\n\t\n\tclass Solution {\n\tpublic:\n int remove(ListNode head, int n)\n {\n if(head==NULL)\n return 0;\n \n int steps | hemarubadeivakani | NORMAL | 2021-10-19T15:18:34.341419+00:00 | 2021-10-20T14:36:22.337345+00:00 | 720 | false | \n\n\n\t\n\tclass Solution {\n\tpublic:\n int remove(ListNode* head, int n)\n {\n if(head==NULL)\n return 0;\n \n int steps = remove(head->next, n); //steps to reach the last node from head->next node\n \n if(steps == n) //if head->next is the node that we need to remove\n head->next = head->next->next; //then remove it\n \n return steps+1;\n }\n\t\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n \n if(remove(head, n) == n) //if head is the node that we need to remove \n head = head->next; \n \n return head;\n }\n\t}; | 9 | 0 | ['Recursion', 'C++'] | 1 |
remove-nth-node-from-end-of-list | Rust 0ms | rust-0ms-by-c0x10-wjgd | \nimpl Solution {\n pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {\n let mut dummy = Box::new(ListNode {\ | c0x10 | NORMAL | 2020-07-08T19:50:39.438183+00:00 | 2020-07-08T19:50:39.438236+00:00 | 603 | false | ```\nimpl Solution {\n pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {\n let mut dummy = Box::new(ListNode {\n val: -1,\n next: head,\n });\n\n let mut right = dummy.clone();\n let mut left = dummy.as_mut();\n\n for _ in 0..n {\n right = right.next.unwrap();\n }\n\n while let Some(node) = right.next {\n right = node;\n left = left.next.as_mut().unwrap();\n }\n\n left.next = left.next.as_mut().unwrap().next.clone();\n\n dummy.next\n }\n}\n``` | 9 | 0 | [] | 2 |
remove-nth-node-from-end-of-list | C++ || 2-Pointers | c-2-pointers-by-abhay5349singh-sngo | Connect with me on LinkedIn: https://www.linkedin.com/in/abhay5349singh/\n\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\ | abhay5349singh | NORMAL | 2023-07-11T03:47:14.301205+00:00 | 2023-07-14T03:34:41.315498+00:00 | 3,366 | false | **Connect with me on LinkedIn**: https://www.linkedin.com/in/abhay5349singh/\n\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 ListNode* removeNthFromEnd(ListNode* head, int k) {\n ListNode *pre_slow, *slow, *fast;\n pre_slow=NULL;\n slow=fast=head;\n \n for(int i=0;i<k;i++) fast=fast->next;\n \n while(fast!=NULL){\n pre_slow=slow;\n slow=slow->next;\n fast=fast->next;\n }\n \n if(pre_slow==NULL){\n ListNode* new_head = head->next;\n delete head;\n return new_head;\n }\n \n pre_slow->next=slow->next;\n slow->next=NULL;\n delete slow;\n \n return head;\n }\n};\n``` | 8 | 0 | ['C++'] | 1 |
remove-nth-node-from-end-of-list | 🗓️ Daily LeetCoding Challenge September, Day 28 | daily-leetcoding-challenge-september-day-w8cc | This problem is the Daily LeetCoding Challenge for September, Day 28. Feel free to share anything related to this problem here! You can ask questions, discuss w | leetcode | OFFICIAL | 2022-09-28T00:00:21.893686+00:00 | 2022-09-28T00:00:21.893760+00:00 | 6,518 | false | This problem is the Daily LeetCoding Challenge for September, Day 28.
Feel free to share anything related to this problem here!
You can ask questions, discuss what you've learned from this problem, or show off how many days of streak you've made!
---
If you'd like to share a detailed solution to the problem, please create a new post in the discuss section and provide
- **Detailed Explanations**: Describe the algorithm you used to solve this problem. Include any insights you used to solve this problem.
- **Images** that help explain the algorithm.
- **Language and Code** you used to pass the problem.
- **Time and Space complexity analysis**.
---
**📌 Do you want to learn the problem thoroughly?**
Read [**⭐ LeetCode Official Solution⭐**](https://leetcode.com/problems/remove-nth-node-from-end-of-list/solution) to learn the 3 approaches to the problem with detailed explanations to the algorithms, codes, and complexity analysis.
<details>
<summary> Spoiler Alert! We'll explain these 2 approaches in the official solution</summary>
**Approach 1:** Two pass algorithm
**Approach 2:** One pass algorithm
</details>
If you're new to Daily LeetCoding Challenge, [**check out this post**](https://leetcode.com/discuss/general-discussion/655704/)!
---
<br>
<p align="center">
<a href="https://leetcode.com/subscribe/?ref=ex_dc" target="_blank">
<img src="https://assets.leetcode.com/static_assets/marketing/daily_leetcoding_banner.png" width="560px" />
</a>
</p>
<br> | 8 | 1 | [] | 55 |
remove-nth-node-from-end-of-list | 2 Different Python Solutions with Explanation | 2-different-python-solutions-with-explan-qkxj | Solution 1: Two Passes\nThe reason why this problem is a medium and not an easy one is because we need to remove the nth node from the end. To do this, we need | alexl5311 | NORMAL | 2022-09-10T16:25:25.185491+00:00 | 2022-09-10T16:26:24.600436+00:00 | 493 | false | # Solution 1: Two Passes\nThe reason why this problem is a medium and not an easy one is because we need to remove the nth node **from the end**. To do this, we need to find the length of the linked list. That is why we need 2 passes: one to find the length of the linked list and another to actually remove the node.\n\nWe first set `i` as the head and iterate the entire list, with each iteration adding 1 to the length. That is really basic.\n\nNow that we have our length, we can remove the node. To remove a node, you set the previous node\'s link to the node after the one we remove. \n\nSay we want to remove node 2: we set 1\'s next link to 3 instead of 2. Therefore the linked list becomes 0, 1, 3.\n```txt\n 0------->1------->2------->3\n 0 1 2 3\n|_|----->|_|-------------->|_|\n```\n\nAlso, the corner case is that `n` is the length, in which we don\'t do anything but return the node after `head`.\n\nNow onto removing the node:\nWe move our `j` pointer to the node **before** the node we want to remove. To do that, we need to mvoe it `length-n-1` times. \n\nOnce we are at that desired node, we just set `j`\'s next pointer to the node after the node we want to remove. \n\nFor those of you who are worried about memory leaks: python has a garbage collection system that\'s automated, so you don\'t have to take care of that.\n```py\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 removeNthFromEnd(self, head, n):\n """\n :type head: ListNode\n :type n: int\n :rtype: ListNode\n """\n i = head\n length = 0\n while i:\n i = i.next\n length += 1\n \n if length == n:\n return head.next\n j = head\n for x in range(length-n-1):\n j = j.next\n j.next = j.next.next\n return head\n```\n\n# Solution 2: One Pass\nThis is the optimal solution: we maintain two pointers and are able to do the entire thing (find length and remove node) in **one pass**.\n\nThe trick is that the distance between the 2 pointers is `n`, so when we have the right pointer at the end, the left pointer will be exactly at the node before the node we want to remove. \n\nNote: to prevent the right node from becoming None (go after the last node), I use `while right.next` instead of `while right` as my loop definition\n\nWe first move the right pointer `n` times, so that the distance between the left and right pointers is `n`.\n\nNow we maintain this "window" and move both pointers until the right pointer is at the end of the list. Now, the left pointer is at the node before the node we want to remove, so we can just remove the node. \n\nIf you want to know how to remove a node, I explain it in the first solution (so scroll up). \n```py\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 removeNthFromEnd(self, head, n):\n """\n :type head: ListNode\n :type n: int\n :rtype: ListNode\n """\n left = right = head\n for i in range(n):\n right = right.next\n \n if not right:\n return left.next\n \n while right.next:\n left = left.next\n right = right.next\n left.next = left.next.next\n return head\n```\n\n**If you liked this, please upvote to support me!** | 8 | 0 | ['Linked List', 'Two Pointers', 'Python'] | 2 |
remove-nth-node-from-end-of-list | [Python3] beats 99.97%- Remove Nth node from list's end | python3-beats-9997-remove-nth-node-from-6jqqo | \nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n first = second = head\n for _ in range(n):\n f | avEraGeC0der | NORMAL | 2021-03-14T17:11:50.139010+00:00 | 2021-03-14T17:13:00.704599+00:00 | 1,196 | false | ```\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n first = second = head\n for _ in range(n):\n first = first.next\n \n if not first:\n return head.next\n while first.next:\n first = first.next\n second = second.next\n \n second.next = second.next.next\n return head\n``` | 8 | 0 | ['Python', 'Python3'] | 2 |
remove-nth-node-from-end-of-list | My C# solution - One pass | my-c-solution-one-pass-by-dani000ooo-wd20 | Runtime: 92 ms, faster than 75.77% of C# online submissions for Remove Nth Node From End of List.\nMemory Usage: 24.8 MB, less than 10.00% of C# online submissi | dani000ooo | NORMAL | 2020-02-09T21:00:24.623669+00:00 | 2020-02-09T21:00:24.623706+00:00 | 983 | false | Runtime: 92 ms, faster than 75.77% of C# online submissions for Remove Nth Node From End of List.\nMemory Usage: 24.8 MB, less than 10.00% of C# online submissions for Remove Nth Node From End of List.\n\n```\npublic ListNode RemoveNthFromEnd(ListNode head, int n) {\n var left = head;\n var right = head;\n\n while(right != null) {\n right = right.next;\n if (n-- < 0) left = left.next; \n } \n\n if (n == 0) head = head.next;\n else left.next = left.next.next;\n\n return head; \n}\n``` | 8 | 0 | [] | 1 |
remove-nth-node-from-end-of-list | My simple java solution | my-simple-java-solution-by-veigar-tuo2 | public class Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n ListNode fast = head;\n ListNode slow = head;\n\t\twhile(f | veigar | NORMAL | 2015-05-26T15:01:14+00:00 | 2015-05-26T15:01:14+00:00 | 1,474 | false | public class Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n ListNode fast = head;\n ListNode slow = head;\n\t\twhile(fast != null) {\n\t\t\tfast = fast.next;\n \tif(n-- < 0) {\n \t\tslow = slow.next;\n \t}\n }\n\t\t\n\t\tif(n == 0) {\n\t\t\thead = head.next;\n\t\t} else if(n < 0) {\n\t\t\tslow.next = slow.next.next;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\treturn head;\n }\n} | 8 | 0 | [] | 0 |
remove-nth-node-from-end-of-list | Java short and clean solution | java-short-and-clean-solution-by-jinwu-ltgn | public class Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n ListNode fast = head, slow = head;\n while (fast != null) | jinwu | NORMAL | 2015-09-10T18:38:01+00:00 | 2015-09-10T18:38:01+00:00 | 1,715 | false | public class Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n ListNode fast = head, slow = head;\n while (fast != null) {\n \tif (n-- < 0) {\n \t\tslow = slow.next;\n \t}\n \tfast = fast.next;\n }\n if (n < 0) \n \tslow.next = slow.next.next;\n else \n \thead = head.next;\n \n return head;\n } } | 8 | 1 | ['Java'] | 0 |
remove-nth-node-from-end-of-list | Simple Python Solution -- One pass | simple-python-solution-one-pass-by-kwu-fccp | # Definition for singly-linked list.\n # class ListNode(object):\n # def __init__(self, x):\n # self.val = x\n # self.next = Non | kwu | NORMAL | 2015-11-19T19:04:45+00:00 | 2018-10-23T09:16:52.853913+00:00 | 2,605 | false | # Definition for singly-linked list.\n # class ListNode(object):\n # def __init__(self, x):\n # self.val = x\n # self.next = None\n \n class Solution(object):\n def removeNthFromEnd(self, head, n):\n """\n :type head: ListNode\n :type n: int\n :rtype: ListNode\n """\n runner = head\n slow = head\n for i in xrange(n):\n runner = runner.next\n if runner is None: # case where n is the length of the list -- remove first node\n head = head.next\n return head\n while runner.next != None:\n runner = runner.next\n slow = slow.next\n slow.next = slow.next.next\n return head | 8 | 0 | ['Python'] | 3 |
remove-nth-node-from-end-of-list | [VIDEO] Visualization of Two-Pointer Solution (One Pass) | video-visualization-of-two-pointer-solut-q4sa | https://www.youtube.com/watch?v=mGTeaxlg69s\n\nThis problem would be a lot easier if n was given in terms of nodes from the front of the list. Then we could si | AlgoEngine | NORMAL | 2024-09-22T03:37:52.547917+00:00 | 2024-09-22T03:37:52.547951+00:00 | 857 | false | https://www.youtube.com/watch?v=mGTeaxlg69s\n\nThis problem would be a lot easier if `n` was given in terms of nodes from the <i>front</i> of the list. Then we could simply traverse the list and stop at the `n-1` node, and make that node skip node `n`.\n\nThe challenge is that since `n` is given in terms of nodes from the <i>end</i> of the list, while we\'re traversing the list, we have no idea when to stop (since we don\'t know the length of the list until we traverse it completely). Then once we\'re at the end of the list, we would like to now go <i>back</i> `n` nodes, but since this is a singly linked list, there is no way to traverse backwards. And now we\'re stuck.\n\nThe solution is to use two pointers, `fast` and `slow`. `fast` will get a head start of `n` nodes, and then we\'ll move up both pointers until `fast` reaches the end of the list. Then at that point, `slow` will be perfectly positioned `n` nodes behind `fast`, and we can use `slow` to make node `n-1` skip node `n` (please see the video for a visualization of this).\n\nIn the worst case, each pointer will traverse the entire list once, so this runs in <b>O(n) time</b>. We will also only ever need 2 extra pointers, so this also runs in <b>O(1) space</b>.\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 removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n fast = head\n slow = head\n for i in range(n):\n fast = fast.next\n \n if not fast:\n return head.next\n \n while fast.next:\n fast = fast.next\n slow = slow.next\n \n slow.next = slow.next.next\n return head\n \n\n``` | 7 | 0 | ['Linked List', 'Two Pointers', 'Python', 'Python3'] | 2 |
remove-nth-node-from-end-of-list | 🔥🔥✅✅||Simple and Easy solution using python✅✅ || Easy To Understand|| With Explanation | simple-and-easy-solution-using-python-ea-3tg9 | PLEASE UPVOTE IF YOU FIGURED IT OUT\n\n# Intuition\nTo remove the Nth node from the end of a singly linked list, we can utilize two pointers - fast and slow. Th | user0517qU | NORMAL | 2024-02-16T20:36:53.208775+00:00 | 2024-02-20T09:50:57.448687+00:00 | 927 | false | # PLEASE UPVOTE IF YOU FIGURED IT OUT\n\n# Intuition\nTo remove the Nth node from the end of a singly linked list, we can utilize two pointers - fast and slow. The fast pointer moves ahead by n + 1 steps initially, creating a gap of n nodes between fast and slow. Then, both pointers move together until the fast pointer reaches the end of the list. At this point, the slow pointer will be pointing to the node just before the node to be removed. We can then remove the Nth node by adjusting the next pointer of the node before it.\n\n# Approach\n- Initialize pointers fast and slow to the dummy node.\n- Move the fast pointer n + 1 steps ahead.\n- Move both pointers together until the fast pointer reaches the end.\n- Adjust the next pointer of the node before the Nth node to skip over it.\n- Return the head of the modified list.\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 using only constant extra space for pointers.\n\n# Code\n```python []\nclass Solution:\n def removeNthFromEnd(self, head, n):\n if head:\n # Create a dummy node to handle edge cases\n dummy = ListNode(0)\n dummy.next = head\n fast = dummy\n slow = dummy\n # Move fast pointer n+1 steps ahead\n for _ in range(n + 1):\n fast = fast.next\n # Move fast to the end, maintaining the gap of n nodes\n while fast:\n fast = fast.next\n slow = slow.next\n # Remove the Nth node from the end\n slow.next = slow.next.next\n # Return the head of the modified list\n return dummy.next\n\n``` | 7 | 0 | ['Python3'] | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.