Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

401
Views
Remove Duplicates from Sorted List in Javascript

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

Input: head = [1,1,2] Output: [1,2]

Solution:

    let curr=head;
    while(curr && curr.next){
        
        if(curr.val===curr.next.val){
            curr.next=curr.next.next;
        }
        else{
            curr=curr.next;
        }
    }
 return head;

I am trying to solve this question on leetcode and found one solution which I am not able to understand one thing, Why are we taking the head in let curr? And, If I am trying to do the same thing without takinghead in another variable then I am getting only [2] as output.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Why are we taking the head in let curr?

For two reasons:

  1. curr needs to be initialised to something, otherwise it will have an undefined value, making the while condition always false, so there will be no iterations and no removals happening.

  2. curr is intended to refer to each (non-duplicate) node one after the other, so it makes sense to start with the first node, which is head.

And, If I am trying to do the same thing without taking head in another variable then I am getting only [2] as output.

That could only happen when you also change the return head by return curr. If you do that, then you will always return a list that has no more than one node, because after the loop has completed, curr will refer to the last node in the list (if it is not empty).

In order to return all nodes in a list, you need to always return its first node, and that is what head represents.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!