Remove Duplicate Elements from Array in C
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Remove Duplicate Elements from Array in C: Program to Delete Duplicates

šŸ“‘ On this page:
  • Introduction
  • C Program to Remove Duplicates
  • Sample Output
  • Program Explanation
  • Algorithm
  • Removing Duplicates from Sorted Array
  • Practice Exercise
  • Frequently Asked Questions
šŸ“š In this tutorial, you will learn:
  • How to remove duplicate elements from an array
  • How to handle unsorted arrays with duplicates
  • How to handle sorted arrays with duplicates
  • Step-by-step explanation of the program
  • Practice exercises to test your understanding

Introduction

In this tutorial, we will learn how to write a C program to remove duplicate elements from an array.

Removing duplicates from an array is a common programming task. It is used in many real-world applications, such as:

  • Cleaning up data by removing repeated entries
  • Creating a unique list of items from a dataset
  • Removing duplicate user records from a database
  • Preparing data for analysis or reporting

šŸ’” Key Point: There are two common approaches to remove duplicates: 1) For unsorted arrays (using nested loops and a visited array) and 2) For sorted arrays (using a single pass with two pointers).

C Program to Remove Duplicates from Unsorted Array

#include <stdio.h>

int main() {
    int n, i, j, k;
    
    // Ask user for number of elements
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    // Declare array
    int arr[n];
    
    // Read elements into the array
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    // Remove duplicates
    for(i = 0; i < n; i++) {
        for(j = i + 1; j < n; j++) {
            if(arr[i] == arr[j]) {
                // Shift all elements to the left
                for(k = j; k < n - 1; k++) {
                    arr[k] = arr[k + 1];
                }
                n--;  // Decrease array size
                j--;  // Check the new element at position j
            }
        }
    }
    
    // Display array after removing duplicates
    printf("\nArray after removing duplicates: ");
    for(i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    return 0;
}

Sample Output

Enter the number of elements: 8
Enter 8 elements:
10 20 10 30 20 40 10 50

Array after removing duplicates: 10 20 30 40 50

Another Example:

Enter the number of elements: 6
Enter 6 elements:
5 5 5 5 5 5

Array after removing duplicates: 5

Example with No Duplicates:

Enter the number of elements: 5
Enter 5 elements:
10 20 30 40 50

Array after removing duplicates: 10 20 30 40 50

Program Explanation

Let's break down the code step by step:

  1. Include Header File: #include <stdio.h> includes the standard input/output library.
  2. Declare Variables:
    • int n; — number of elements
    • int i, j, k; — loop counters
  3. Get User Input: Reads the array elements from the user.
  4. Remove Duplicates:
    • The outer loop (i) iterates through each element
    • The inner loop (j) checks for duplicates of arr[i] in the remaining array
    • If a duplicate is found (arr[i] == arr[j]):
      • Shift all elements from j+1 to n-1 one position left
      • Decrease n by 1 (array size reduced)
      • Decrease j by 1 to check the new element at position j
  5. Display Result: Prints the array after removing duplicates.
  6. Return: return 0; indicates successful program execution.

šŸ“ Note: This method modifies the original array. The variable n is updated to reflect the new size after removing duplicates.

Algorithm to Remove Duplicates (Unsorted Array)

Step-by-step algorithm:

  1. Start
  2. Read the array elements
  3. For i = 0 to n-1:
    • For j = i+1 to n-1:
      • If arr[i] == arr[j]:
        • For k = j to n-2:
          • arr[k] = arr[k+1]
        • n--
        • j--
  4. Print the updated array
  5. End

Alternative Method: Using Visited Array

This method uses a separate array to track which elements have already been added to the result.

#include <stdio.h>

int main() {
    int n, i, j;
    int count = 0;
    
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    int arr[n];
    int visited[n];  // To mark visited elements
    int unique[n];   // To store unique elements
    
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
        visited[i] = 0;
    }
    
    // Find unique elements
    for(i = 0; i < n; i++) {
        if(visited[i] == 0) {
            unique[count] = arr[i];
            count++;
            
            // Mark all duplicates as visited
            for(j = i + 1; j < n; j++) {
                if(arr[i] == arr[j]) {
                    visited[j] = 1;
                }
            }
        }
    }
    
    // Display unique elements
    printf("\nArray after removing duplicates: ");
    for(i = 0; i < count; i++) {
        printf("%d ", unique[i]);
    }
    printf("\n");
    
    return 0;
}

Removing Duplicates from a Sorted Array

If the array is already sorted, we can remove duplicates in O(n) time using a two-pointer approach.

#include <stdio.h>

int main() {
    int n, i, j;
    
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    int arr[n];
    
    printf("Enter %d sorted elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    // Remove duplicates from sorted array
    j = 0;
    for(i = 1; i < n; i++) {
        if(arr[i] != arr[j]) {
            j++;
            arr[j] = arr[i];
        }
    }
    
    // j+1 is the new size
    int newSize = j + 1;
    
    printf("\nArray after removing duplicates: ");
    for(i = 0; i < newSize; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    return 0;
}

Sample Output:

Enter the number of elements: 8
Enter 8 sorted elements:
10 10 20 20 30 40 40 50

Array after removing duplicates: 10 20 30 40 50

How Sorted Array Approach Works

  • Two Pointers: j tracks the position of the last unique element
  • Compare: If arr[i] != arr[j], it's a new unique element
  • Copy: Copy the new element to position j+1
  • Increment: Move j forward
  • Result: The first j+1 elements are unique

Time and Space Complexity

Method Time Complexity Space Complexity
Nested Loop (Unsorted) O(n²) O(1)
Visited Array O(n²) O(n)
Sorted Array (Two-Pointer) O(n) O(1)

šŸ’» Practice Exercise

Challenge 1: Modify the program to remove duplicates and sort the array in ascending order.

Challenge 2: Count the number of duplicate elements removed from the array.

šŸ” Click to Show Solution for Challenge 2
#include <stdio.h>

int main() {
    int n, i, j, k;
    int duplicates_removed = 0;
    
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    int arr[n];
    
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    int original_n = n;
    
    // Remove duplicates and count
    for(i = 0; i < n; i++) {
        for(j = i + 1; j < n; j++) {
            if(arr[i] == arr[j]) {
                for(k = j; k < n - 1; k++) {
                    arr[k] = arr[k + 1];
                }
                n--;
                j--;
                duplicates_removed++;
            }
        }
    }
    
    printf("\nArray after removing duplicates: ");
    for(i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    printf("Total duplicates removed: %d\n", duplicates_removed);
    printf("Original size: %d, New size: %d\n", original_n, n);
    
    return 0;
}

Frequently Asked Questions

1. How do you remove duplicate elements from an array in C?

You can use nested loops to check for duplicates and shift elements to the left. For sorted arrays, use the two-pointer approach. For unsorted arrays, you can also use a visited array.

2. What is the most efficient way to remove duplicates?

For sorted arrays, the two-pointer approach is the most efficient with O(n) time and O(1) space. For unsorted arrays, consider sorting first and then using the two-pointer approach.

3. Does the program maintain the original order of elements?

Yes, the nested loop method maintains the original order of the first occurrence of each element. The sorted array method also maintains order.

4. What happens if all elements are the same?

If all elements are the same, the array will contain only one element after removing duplicates.

5. Can I use this method for strings?

Yes, the same logic can be applied to arrays of strings using strcmp() instead of == for comparison.

šŸ’” Tip: For large unsorted arrays, consider sorting the array first and then removing duplicates using the two-pointer approach for better performance.

šŸ“– Related Tutorials

  • Find Second Largest Element
  • Intersection of Two Arrays
  • Union of Two Arrays
  • More Array Assignments

Previous Topic: -->> Find Second Largest Element   ||   Next topic: -->> Intersection of Two Arrays


šŸ“š Explore More Topics

šŸ—„ļø SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

šŸ Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

ā˜• Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.