I was asked to code for the following problem:
Problem Description:
Given a linked list, find the number of duplicate elements in the list.
Input Format:
First line contains an integer
N- The number of nodes.Second line contains
Nintegers - Node values.Output Format:
Print the total number of duplicates.
Constraints:
N <= 10^5Value of node <=
10^6
Sample Input:
9
1 2 3 4 4 5 6 6 6
Sample Output:
3
Explanation:
In the given test case we have 3 duplicates i.e. one 4 and two 6.
My code:
import crio.ds.List.*;
/*public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) { val = x; next = null; }
}*/
public class Solution {
public int countDuplicatesInALinkedList(ListNode head){
int counter = 0;
while(head.next != null){
ListNode ptr = head.next;
while(ptr != null){
if(head.val == ptr.val){
counter++;
break;
}
ptr = ptr.next;
}
head = head.next;
}
return counter;
}
}
I want to understand why my code is failing the edge case.