Simple SWIFT Solution in only 1 loop


  • 0
    I
    class Solution {
        func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
            var res = head
            var map = [Int: ListNode]()
            var i = 0
            while res != nil {
                map[i] = res
                i += 1
                res = res?.next
            }
            res = head
            if n == map.count { return res?.next }
            let removeIndex = map.count - n
            
            map[removeIndex-1]?.next = map[removeIndex]?.next
            
            return res
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.