Remove Nth Node From End of List

Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Input: head = [1], n = 1
Output: []
Input: head = [1,2], n = 1
Output: [1]
  • The number of nodes in the list is sz.
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz
class Solution(object):
def removeNthFromEnd(self, head, n):
inter,inter.next=ListNode(0),head
head,cnt=inter,0
ptr1,ptr2=head,head
while(cnt!=n):
cnt+=1
ptr1=ptr1.next
while(ptr1.next):
ptr1=ptr1.next
ptr2=ptr2.next
ptr2.next=ptr2.next.next
return (head.next)
class Solution(object):
def removeNthFromEnd(self, head, n):
ptr1=head
cnt=0
while(ptr1):
cnt+=1
ptr1=ptr1.next
if cnt-n==0:
return head.next
val=0
ptr2=head
while(val!=cnt-n-1):
val+=1
ptr2=ptr2.next
ptr2.next=ptr2.next.next
return head
class Solution(object):
def removeNthFromEnd(self, head, n):
def rec(curr,n):
if not curr:
return -1
ind=rec(curr.next,n)+1
if ind ==n:
curr.next=curr.next.next
return ind
inter=ListNode(0)
inter.next=head
head=inter
rec(head,n)
return inter.next

Tech-Enthusiast, Coder,Explorer,Geeky,Software Engineer |A piece of code delivers everything that you need. The world is all about codes.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to Solve the Average Pair Problem

Object-Oriented JavaScript — Parts of a Class

Using the React Children Prop to Create Reusable Layout Components

Basic JavaScript Concepts Front End Development — Arrays and More

The Case Of A Serverless Single-Page React App

JavaScript Best Practices for Writing More Robust Code — Avoiding Bad Code

React vs Angular

JavaScript Refactoring Tips — Arrays and Conditionals

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dhanarajappu

Dhanarajappu

Tech-Enthusiast, Coder,Explorer,Geeky,Software Engineer |A piece of code delivers everything that you need. The world is all about codes.

More from Medium

Minimum cost to reach the top

What Big O Notation Can Teach Us About Dealing With Life’s Challenges

Topological Sort — BFS Vs DFS

Leetcode 701. Insert into a Binary Search Tree