Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Print all Unique Strings present in a given Array
Next article icon

Print all unique elements present in a sorted array

Last Updated : 20 Oct, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a sorted array arr[] of size N, the task is to print all the unique elements in the array.

An array element is said to be unique if the frequency of that element in the array is 1.

Examples:

Input: arr[ ] = {1, 1, 2, 2, 3, 4, 5, 5}
Output: 3 4
Explanation: Since 1, 2, 5 are occurring more than once in the array, the distinct elements are 3 and 4.

Input: arr[ ] = {1, 2, 3, 3, 3, 4, 5, 6}
Output: 1 2 4 5 6

Approach: The simplest approach to solve the problem is to traverse the array arr[] and print only those elements whose frequency is 1. Follow the steps below to solve the problem:

  • Iterate over the array arr[] and initialize a variable, say cnt = 0,   to count the frequency of the current array element.
  • Since the array is already sorted, check if the current element is the same as the previous element. If found to be true, then update cnt += 1.
  • Otherwise, if cnt = 1, then print the element. Otherwise, continue.

Below is the implementation of the above approach:

C++
// C++ Program for the above approach #include <bits/stdc++.h> using namespace std;  // Function to print all unique // elements present in a sorted array void RemoveDuplicates(int arr[], int n) {      int i = 0;      // Traverse the array     while (i < n) {          int cur = arr[i];          // Stores frequency of         // the current element         int cnt = 0;          // Iterate until end of the         // array is reached or current         // element is not the same as the         // previous element         while (i < n and cur == arr[i]) {             cnt++;             i++;         }          // If current element is unique         if (cnt == 1) {              cout << cur << " ";         }     } }  // Driver Code int main() {      // Given Input     int arr[] = { 1, 3, 3, 5, 5, 6, 10 };     int N = 7;      // Function Call     RemoveDuplicates(arr, N);      return 0; } 
Java
// Java Program for the above approach import java.io.*;  class GFG  {      // Function to print all unique   // elements present in a sorted array   static void RemoveDuplicates(int arr[], int n)   {      int i = 0;      // Traverse the array     while (i < n) {        int cur = arr[i];        // Stores frequency of       // the current element       int cnt = 0;        // Iterate until end of the       // array is reached or current       // element is not the same as the       // previous element       while (i < n && cur == arr[i]) {         cnt++;         i++;       }        // If current element is unique       if (cnt == 1) {         System.out.print(cur +" ");       }     }   }    // Driver Code    public static void main (String[] args)   {      // Given Input     int arr[] = { 1, 3, 3, 5, 5, 6, 10 };     int N = 7;      // Function Call     RemoveDuplicates(arr, N);   } }  // This code is contributed by Potta Lokesh 
Python3
# Function to print all unique # elements present in a sorted array def RemoveDuplicates(arr, n):     i = 0     while i < n:         cur = arr[i]                  # Stores frequency of         # the current element         cnt = 0          # Iterate until end of the         # array is reached or current         # element is not the same as the         # previous element         while i < n and cur == arr[i]:             cnt += 1             i += 1         if cnt == 1:             print(cur, end=" ")  # Driver code if __name__ == "__main__":        # Given Input     arr = [1, 3, 3, 5, 5, 6, 10]     N = 7      # Function Call     RemoveDuplicates(arr, N)      # This code is contributed by Kushagra Bansal 
C#
// C# Program for the above approach using System;  class GFG {      // Function to print all unique     // elements present in a sorted array     static void RemoveDuplicates(int[] arr, int n)     {          int i = 0;          // Traverse the array         while (i < n) {              int cur = arr[i];              // Stores frequency of             // the current element             int cnt = 0;              // Iterate until end of the             // array is reached or current             // element is not the same as the             // previous element             while (i < n && cur == arr[i]) {                 cnt++;                 i++;             }              // If current element is unique             if (cnt == 1) {                 Console.Write(cur + " ");             }         }     }      // Driver Code      public static void Main()     {          // Given Input         int[] arr = { 1, 3, 3, 5, 5, 6, 10 };         int N = 7;          // Function Call         RemoveDuplicates(arr, N);     } }  // This code is contributed by rishavmahato348. 
JavaScript
 <script>         // JavaScript Program for the above approach          // Function to print all unique         // elements present in a sorted array         function RemoveDuplicates(arr, n) {              let i = 0;              // Traverse the array             while (i < n) {                  let cur = arr[i];                  // Stores frequency of                 // the current element                 let cnt = 0;                  // Iterate until end of the                 // array is reached or current                 // element is not the same as the                 // previous element                 while (i < n && cur == arr[i]) {                     cnt++;                     i++;                 }                  // If current element is unique                 if (cnt == 1) {                      document.write(cur + " ");                 }             }         }          // Driver Code          // Given Input         let arr = [1, 3, 3, 5, 5, 6, 10];         let N = 7;          // Function Call         RemoveDuplicates(arr, N);      // This code is contributed by Potta Lokesh      </script> 

Output
1 6 10 

Time Complexity: O(N)
Auxiliary Space: O(1)


Next Article
Print all Unique Strings present in a given Array
author
hrithikgarg03188
Improve
Article Tags :
  • Misc
  • Mathematical
  • School Programming
  • DSA
  • Arrays
  • frequency-counting
Practice Tags :
  • Arrays
  • Mathematical
  • Misc

Similar Reads

  • Print all Unique Strings present in a given Array
    Given an array of strings arr[], the task is to print all unique strings that are present in the given array. Examples: Input: arr[] = { "geeks", "geek", "ab", "geek" "code", "karega" } Output: geeks ab code karega Explanation: The frequency of the string "geeks" is 1. The frequency of the string "g
    15+ min read
  • LCM of unique elements present in an array
    Given an array arr[] consisting of N positive integers, the task is to find the LCM of all unique elements of the given array. If the array does not contain any unique elements, then print "-1". Examples: Input: arr[] = {1, 2, 1, 3, 3, 4}Output: 4Explanation: The unique elements of the given array a
    8 min read
  • Print all Distinct (Unique) Elements in given Array
    Given an integer array arr[], print all distinct elements from this array. The given array may contain duplicates and the output should contain every element only once. Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45}Output: {12, 10, 9, 45, 2} Input: arr[] = {1, 2, 3, 4, 5}Output: {1, 2, 3, 4
    11 min read
  • Count of Unique elements in a very large sorted Array
    Given a sorted array arr[] of size N, the task is to find the number of unique elements in this array. Note: The array is very large, and unique numbers are significantly less. i.e., (unique elements <<size of the array). Examples: Input: arr[] = {1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8
    11 min read
  • Single Element in a Sorted Array
    Given a sorted array in which all elements appear twice and one element appears only once, the task is to find the element that appears once. Examples: Input: arr[] = {1, 1, 3, 3, 4, 5, 5, 7, 7, 8, 8}Output: 4Explanation: All numbers except 4 occur twice in the array. Input: arr[] = {1, 1, 3, 3, 4,
    11 min read
  • Find the frequency of each element in a sorted array
    Given a sorted array, arr[] consisting of N integers, the task is to find the frequencies of each array element. Examples: Input: arr[] = {1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10} Output: Frequency of 1 is: 3 Frequency of 2 is: 1 Frequency of 3 is: 2 Frequency of 5 is: 2 Frequency of 8 is: 3 Frequ
    10 min read
  • Print uncommon elements from two sorted arrays
    Given two sorted arrays of distinct elements, we need to print those elements from both arrays that are not common. The output should be printed in sorted order. Examples : Input : arr1[] = {10, 20, 30} arr2[] = {20, 25, 30, 40, 50} Output : 10 25 40 50 We do not print 20 and 30 as these elements ar
    6 min read
  • All elements in an array are Same or not?
    Given an array, check whether all elements in an array are the same or not. Examples: Input : "Geeks", "for", "Geeks" Output : Not all Elements are Same Input : 1, 1, 1, 1, 1 Output : All Elements are Same Method 1 (Hashing): We create an empty HashSet, insert all elements into it, then we finally s
    5 min read
  • Find Number of Unique Elements in an Array After each Query
    Given 2d array A[][1] of size N and array Q[][2] of size M representing M queries of type {a, b}. The task for this problem is in each query move all elements from A[a] to A[b] and print the number of unique elements in A[b]. Constraints: 1 <= N, Q <= 1051 <= A[i] <= 1091 <= a, b <
    10 min read
  • Find all indices of a given element in sorted form of given Array
    Given an array arr[] of integers of size N and a target value val. Your task is to find the indices of val in the array after sorting the array in increasing order. Note: The indices must be in increasing order. Examples: Input: arr = [1, 2, 5, 2, 3], val = 2Output: 1 2Explanation: After sorting, ar
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences