The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
+13 votes

Consider the following piece of  'C' code fragment that removes duplicates from an ordered list of integers.

Node *remove-duplicates (Node* head, int *j)
    Node *t1, *t2; *j=0; 
    t1 = head; 
    if (t1! = NULL) 
        t2 = t1 ->next; 
    else return head;
    *j = 1; 
    if(t2 == NULL) return head; 
    while (t2 != NULL) 
        if (t1.val != t2.val) ----------------> (S1) 
            t1 -> next = t2; 
            t1 = t2; -----> (S2) 
            t2 = t2 ->next; 
    t1 -> next = NULL; 
    return head; 

Assume the list contains $n$ elements ($n\geq 2$) in the following questions.

How many times is the comparison in statement $S1$ made?

What is the minimum and the maximum number of times statements marked $S2$ get executed?

What is the significance of the value in the integer pointed to by $j$ when the function completes?

asked in DS by Veteran (59.6k points)
edited by | 753 views
Please explain...

3 Answers

+14 votes
Best answer
  1. As we are comparing here pair wise so for $n$ elements we require compulsory  $n-1$ comparison
  2. $S2$ is executed only for distinct elements so max $n-1$ times and min $0$ when all $r$ duplicates or list contain no or $1$ element.
  3. $j$ holds the count on number of distinct elements in the ordered list.
answered by Boss (22.9k points)
edited by
Isn't assigning an integer value such as 1 to a pointer a bad way of doing things?
*j=1 here * is  not representing pointer, but it is value at operator or Dereferencing operator.
+3 votes

1. n elements are compared n-1 times. Finding larger of 2 numbers is done in 1 comparison, for 3 in 2 comparisons and so on.  (Ans : n-1)

2. S2 executes when values at t1 & t2 are unequal.

Case Max : no duplicate element in list. (Ans : n-1)

Case Min : All nodes have same value. (Ans : 0)

3. Value at j is incremented every time t1 and t2 contain unequal values. Hence, j keeps a count of distinct elements in the list.

answered by Active (2.1k points)
edited by
+2 votes

Since every time the statement s1 will get executed so max n-1 comparisons

S2 willl be executed when statement s1 is true if all the element in list is same than 0 times s2 will be executed and n-1 times atmost

j is determining The Number  of the pair which are not identical


Tell me if i am wrong
answered by (31 points)
Here Ur explanation of C is incorrect when there is only 1 node @ time
j should be 1 while ur ans saying abt pairs and when there is only one node there is 0 pairs.

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

40,845 questions
47,506 answers
62,261 users