Home › Company-wise questions › Microsoft › Remove Duplicates from Sorted List II ← Microsoft bank
Microsoft · Question 22 · Linked Lists
Remove Duplicates from Sorted List II Linked Lists Java code ⏱ O(n) 💾 O(1)
Product-based Published and maintained by DSA-topics · Last updated 30 November 2026 · Report an error
About this bank These are classic technical-interview concepts compiled from publicly circulated company-wise question sets, rewritten with original explanations and compiler-ready solutions for educational practice; inclusion does not imply endorsement by the company. Spotted an error? Tell us .
Problem Remove all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Approach Skip entire duplicate runs using a dummy head.
Time O(n)Space O(1)
How it works 1 Detect a duplicate run and jump the whole run. 2 Singletons are linked through prev. Sample input / output Input:
7
1 2 3 3 4 4 5
Output:
[1, 2, 5] Constraints 0 <= nodes <= 300; sorted list.
Solution — read it, then walk it Flowchart Pseudocode
Time O(n)Space O(1)Loops 5Branches 1Returns 3source · Java
Scroll sideways for wide charts — the view follows the active step. ⤢ Expand
yes no ↻ repeat ↻ repeat START import java.util.* DEFINE class Main DEFINE static ListNode deleteDuplicates(ListNode head) ListNode dummy = new ListNode(0) dummy.next = head ListNode prev = dummy while (head != null) if (head.next != null && head.val == head.next.val) while (head.next != null && head.val == head.next.val) head = head.next prev.next = head.next } else head = head.next RETURN dummy.next DEFINE class ListNode DEFINE val ListNode next ListNode(int v) { val = v; } DEFINE ListNode buildList(int[] values) ListNode dummy = new ListNode(0), tail = dummy for (int v : values) { tail.next = new ListNode(v); tail … RETURN dummy.next DEFINE String toList(ListNode head) StringBuilder sb = new StringBuilder("[") while (head != null) { sb.append(head.val); head = head.next; i… RETURN sb.append("]").toString() DEFINE static void main(String[] args) java.util.Scanner sc = new java.util.Scanner(System.in) DEFINE n = sc.nextInt() DEFINE [] vals = new int[n] for (int i = 0; i < vals.length; i++) vals[i] = sc.nextInt() System.out.println(toList(deleteDuplicates(buildList(vals)))) END start / end statement condition loop returns definition← Q21 · Remove Duplicates from Sorted List Q23 · Intersection of Two Linked Lists → Solution code Core logic highlighted in green
Language Python Javasource C++ C Core logic Full code Copy
Recommended resources Affiliate links · may earn us a commission
Classic DSA interview books The reference books interviewers themselves learned from — great next to the visualizers. See the books → Structured coding courses Video courses that pair well with visual practice — pick one language and go deep. Browse courses → Cloud hosting for side projects Ship the portfolio project that gets you hired — free credits for new accounts. Claim credits →