LeetCode: Remove Duplicates from Sorted List Solution

Keep jump over next node until values are not equal

Approach

Keep jump over next node until values are not equal

Implementation

1var deleteDuplicates = function (head) {
2 let node = head
3
4 while (node) {
5 while (node.next && node.val === node.next.val) {
6 node.next = node.next.next
7 }
8 node = node.next
9 }
10
11 return head
12}

Implementation (recursive)

Note the recursive solution

  • it would be less painful to understand if we draw it down
  • one thing to remember,
    return
    statement of first call will run last
1var deleteDuplicates = function (head) {
2 if (!head) return null
3 head.next = deleteDuplicates(head.next)
4 return head.next && head.next.val === head.val ? head.next : head
5}

Comments

Loading comments...

Tags

leetcode

linked list

recursion

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Check If String Is a Prefix of Array

Aug 27, 2021

Accumulated concatenation and check

Previous Post

LeetCode: Binary Tree Inorder Traversal

Aug 26, 2021

Recursive or iterative (stack)

HoningJS

Search Posts