The Wayback Machine - https://web.archive.org/web/20240915174332/https://www.geeksforgeeks.org/print-distinct-elements-given-integer-array/
Open In App

Print all Distinct ( Unique ) Elements in given Array

Last Updated : 28 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Solve Problem
Basic
49.37%
12.2K

Given an integer array, print all distinct elements in an array. The given array may contain duplicates and the output should print every element only once. The given array is not sorted.

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, 5

Input: arr[] = {1, 1, 1, 1, 1}
Output: 1

Print all Distinct ( Unique ) Elements in given Array using Nested loop:

A Simple Solution is to use two nested loops. The outer loop picks an element one by one starting from the leftmost element. The inner loop checks if the element is present on left side of it. If present, then ignores the element, else prints the element. Following is the implementation of the simple algorithm. 

Implementation:

C++




// C++ program to print all distinct elements in a given array
#include <bits/stdc++.h>
using namespace std;
 
void printDistinct(int arr[], int n)
{
    // Pick all elements one by one
    for (int i=0; i<n; i++)
    {
        // Check if the picked element is already printed
        int j;
        for (j=0; j<i; j++)
           if (arr[i] == arr[j])
               break;
 
        // If not printed earlier, then print it
        if (i == j)
          cout << arr[i] << " ";
    }
}
 
// Driver program to test above function
int main()
{
    int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10};
    int n = sizeof(arr)/sizeof(arr[0]);
    printDistinct(arr, n);
    return 0;
}


Java




// Java program to print all distinct
// elements in a given array
import java.io.*;
 
class GFG {
 
    static void printDistinct(int arr[], int n)
    {
        // Pick all elements one by one
        for (int i = 0; i < n; i++)
        {
            // Check if the picked element
            // is already printed
            int j;
            for (j = 0; j < i; j++)
            if (arr[i] == arr[j])
                break;
     
            // If not printed earlier,
            // then print it
            if (i == j)
            System.out.print( arr[i] + " ");
        }
    }
     
    // Driver program
    public static void main (String[] args)
    {
        int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10};
        int n = arr.length;
        printDistinct(arr, n);
 
    }
}
 
// This code is contributed by vt_m


Python3




# python program to print all distinct
# elements in a given array
 
def printDistinct(arr, n):
 
    # Pick all elements one by one
    for i in range(0, n):
 
        # Check if the picked element
        # is already printed
        d = 0
        for j in range(0, i):
            if (arr[i] == arr[j]):
                d = 1
                break
 
        # If not printed earlier,
        # then print it
        if (d == 0):
            print(arr[i])
     
# Driver program to test above function
arr = [6, 10, 5, 4, 9, 120, 4, 6, 10]
n = len(arr)
printDistinct(arr, n)
 
# This code is contributed by Sam007.


C#




// C# program to print all distinct
// elements in a given array
using System;
 
class GFG {
 
    static void printDistinct(int []arr, int n)
    {
         
        // Pick all elements one by one
        for (int i = 0; i < n; i++)
        {
             
            // Check if the picked element
            // is already printed
            int j;
            for (j = 0; j < i; j++)
                if (arr[i] == arr[j])
                     break;
     
            // If not printed earlier,
            // then print it
            if (i == j)
            Console.Write(arr[i] + " ");
        }
    }
     
    // Driver program
    public static void Main ()
    {
        int []arr = {6, 10, 5, 4, 9, 120,
                                  4, 6, 10};
        int n = arr.Length;
         
        printDistinct(arr, n);
 
    }
}
 
// This code is contributed by Sam007.


Javascript




<script>
//Program to print all distinct elements in a given array
 
   
    function  printDistinct(arr, n)
{
    // Pick all elements one by one
    for (let i=0; i<n; i++)
    {
        // Check if the picked element is already printed
        var j;
        for (j=0; j<i; j++)
           if (arr[i] == arr[j])
               break;
   
        // If not printed earlier, then print it
        if (i == j)
          document.write(arr[i] + " ");
    }
}
   
// Driver program to test above function
    arr = new Array(6, 10, 5, 4, 9, 120, 4, 6, 10);
    n = arr.length;
    printDistinct(arr, n);
//This code is contributed by simranarora5sos
</script>


PHP




<?php
// PHP program to print all distinct
// elements in a given array
 
function printDistinct($arr, $n)
{
    // Pick all elements one by one
    for($i = 0; $i < $n; $i++)
    {
         
        // Check if the picked element
        // is already printed
        $j;
        for($j = 0; $j < $i; $j++)
        if ($arr[$i] == $arr[$j])
            break;
 
        // If not printed
        // earlier, then print it
        if ($i == $j)
        echo $arr[$i] , " ";
    }
}
 
    // Driver Code
    $arr = array(6, 10, 5, 4, 9, 120, 4, 6, 10);
    $n = sizeof($arr);
    printDistinct($arr, $n);
     
// This code is contributed by nitin mittal
?>


Output

6 10 5 4 9 120 




Time Complexity: O(n2). 
Auxiliary Space: O(1), since no extra space has been taken.

Print all Distinct ( Unique ) Elements in given Array using using Sorting :

We can use Sorting to solve the problem in O(N log N) time. The idea is simple, first sort the array so that all occurrences of every element become consecutive. Once the occurrences become consecutive, we can traverse the sorted array and print distinct elements in O(n) time. Following is the implementation of the idea. 

Implementation:

C++




// C++ program to print all distinct elements in a given array
#include <bits/stdc++.h>
using namespace std;
 
void printDistinct(int arr[], int n)
{
    // First sort the array so that all occurrences become consecutive
    sort(arr, arr + n);
 
    // Traverse the sorted array
    for (int i=0; i<n; i++)
    {
       // Move the index ahead while there are duplicates
       while (i < n-1 && arr[i] == arr[i+1])
          i++;
 
       // print last occurrence of the current element
       cout << arr[i] << " ";
    }
}
 
// Driver program to test above function
int main()
{
    int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10};
    int n = sizeof(arr)/sizeof(arr[0]);
    printDistinct(arr, n);
    return 0;
}


Java




// Java program to print all distinct
// elements in a given array
import java.io.*;
import java .util.*;
 
class GFG
{
    static void printDistinct(int arr[], int n)
    {
        // First sort the array so that
        // all occurrences become consecutive
        Arrays.sort(arr);
     
        // Traverse the sorted array
        for (int i = 0; i < n; i++)
        {
            // Move the index ahead while
            // there are duplicates
            while (i < n - 1 && arr[i] == arr[i + 1])
                i++;
     
            // print last occurrence of
            // the current element
            System.out.print(arr[i] +" ");
        }
    }
     
    // Driver program
    public static void main (String[] args)
    {
        int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10};
        int n = arr.length;
        printDistinct(arr, n);
 
    }
}
 
// This code is contributed by vt_m


Python3




# Python program to print all distinct
# elements in a given array
 
def printDistinct(arr, n):
     
    # First sort the array so that
    # all occurrences become consecutive
    arr.sort();
 
    # Traverse the sorted array
    for i in range(n):
         
        # Move the index ahead while there are duplicates
        if(i < n-1 and arr[i] == arr[i+1]):
            while (i < n-1 and (arr[i] == arr[i+1])):
                i+=1;
             
 
        # print last occurrence of the current element
        else:
            print(arr[i], end=" ");
 
# Driver code
arr = [6, 10, 5, 4, 9, 120, 4, 6, 10];
n = len(arr);
printDistinct(arr, n);
 
# This code has been contributed by 29AjayKumar


C#




// C# program to print all distinct
// elements in a given array
using System;
 
class GFG {
 
    static void printDistinct(int []arr, int n)
    {
         
        // First sort the array so that
        // all occurrences become consecutive
        Array.Sort(arr);
     
        // Traverse the sorted array
        for (int i = 0; i < n; i++)
        {
             
            // Move the index ahead while
            // there are duplicates
            while (i < n - 1 && arr[i] == arr[i + 1])
                i++;
     
            // print last occurrence of
            // the current element
            Console.Write(arr[i] + " ");
        }
    }
     
    // Driver program
    public static void Main ()
    {
        int []arr = {6, 10, 5, 4, 9, 120, 4, 6, 10};
        int n = arr.Length;
         
        printDistinct(arr, n);
    }
}
 
// This code is contributed by Sam007.


Javascript




<script>
 
// JavaScript program to print all
// distinct elements in a given array
 
function printDistinct(arr, n)
{
    // First sort the array so that all
    // occurrences become consecutive
    arr.sort((a, b) => a - b);
 
    // Traverse the sorted array
    for (let i=0; i<n; i++)
    {
    // Move the index ahead while
    // there are duplicates
    while (i < n-1 && arr[i] == arr[i+1])
        i++;
 
    // print last occurrence of the
    // current element
    document.write(arr[i] + " ");
    }
}
 
// Driver program to test above function
    let arr = [6, 10, 5, 4, 9, 120, 4, 6, 10];
    let n = arr.length;
    printDistinct(arr, n);
 
 
// This code is contributed by Surbhi Tyagi.
 
</script>


PHP




<?php
// PHP program to print all distinct
// elements in a given array
 
function printDistinct( $arr, $n)
{
     
    // First sort the array so
    // that all occurrences
    // become consecutive
    sort($arr);
 
    // Traverse the sorted array
    for ($i = 0; $i < $n; $i++)
    {
         
        // Move the index ahead
        // while there are duplicates
        while ($i < $n - 1 and
               $arr[$i] == $arr[$i + 1])
            $i++;
     
        // print last occurrence
        // of the current element
        echo $arr[$i] , " ";
    }
}
 
    // Driver Code
    $arr = array(6, 10, 5, 4, 9, 120, 4, 6, 10);
    $n = count($arr);
    printDistinct($arr, $n);
 
// This code is contributed by anuj_67.
?>


Output

4 5 6 9 10 120 




Time Complexity: O(n log n).
Auxiliary Space: O(1)

Print all Distinct ( Unique ) Elements in given Array using Set :

The Easiest Way to do it is to take a vector input then put the vector into a set and just traverse over the set.

C++




#include <iostream>
#include<bits/stdc++.h>
using namespace std;
 
int main() {
    vector<int>v{10, 5, 3, 4, 3, 5, 6};
    set<int>s(v.begin(),v.end());
    cout<<"All the distinct element in given vector in sorted order are: ";
    for(auto it:s)cout<<it<<" ";
    cout<<endl;
  return 0;
}


Java




import java.io.*;
import java .util.*;
 
class GFG
{
  public static void main (String[] args)
  {
    List<Integer>v = new ArrayList<Integer>();
    v.add(10);
    v.add(5);
    v.add(3);
    v.add(4);
    v.add(3);
    v.add(5);
    v.add(6);
 
    SortedSet<Integer> s = new TreeSet<Integer>();
 
    for(int i=0; i<v.size(); i++)
      s.add(v.get(i));
 
    System.out.print("All the distinct element in given vector in sorted order are: ");
    for (Integer value : s)
      System.out.print(value+" ");
  }
}
 
// This code is contributed by ratiagrawal.


Python3




from sortedcontainers import SortedList, SortedSet, SortedDict
 
v=[10, 5, 3, 4, 3, 5, 6];
s=SortedSet();
for i in range (0,len(v)):
    s.add(v[i]);
print("All the distinct element in given vector in sorted order are: ");
for it in s:
    print(it," ");


C#




// C# code to implement the approach
using System;
using System.Collections.Generic;
 
class GFG {
 
  public static void Main()
  {
    int[] v = {10, 5, 3, 4, 3, 5, 6};
    SortedSet<int> s = new SortedSet<int>();
 
    for(int i = 0; i < v.Length; i++)
      s.Add(v[i]);
    Console.Write("All the distinct element in given vector in sorted order are: ");
    foreach (int res in s)
      Console.Write(res+" ");
  }
}
 
// This code is contributed by poojaagrawal2.


Javascript




// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)
// JavaScript Program for the above approach
let v = [10, 5, 3, 4, 3, 5, 6];
v.sort(function(a,b){return a-b});
let s = new Set(v);
document.write("All the distinct element in given vector in sorted order are : ");
s.forEach(function(value){
    document.write(value + " ");
});


Output

All the distinct element in given vector in sorted order are: 3 4 5 6 10 




Time Complexity: O(N.log N).
Auxiliary Space: O(N), for a set.

Print all Distinct ( Unique ) Elements in given Array using Hashing :

We can Use Hashing to solve this in O(n) time on average. The idea is to traverse the given array from left to right and keep track of visited elements in a hash table. Following is the implementation of the idea.

Implementation:

C++




/* CPP program to print all distinct elements
   of a given array */
#include<bits/stdc++.h>
using namespace std;
 
// This function prints all distinct elements
void printDistinct(int arr[],int n)
{
    // Creates an empty hashset
    unordered_set<int> s;
 
    // Traverse the input array
    for (int i=0; i<n; i++)
    {
        // if element is not present then s.count(element) return 0 else return 1
        // hashtable and print it
        if (!s.count(arr[i]))  // <--- avg O(1) time
        {
            s.insert(arr[i]);
            cout << arr[i] << " ";
        }
    }
}
 
// Driver method to test above method
int main ()
{
    int arr[] = {10, 5, 3, 4, 3, 5, 6};
    int n=7;
    printDistinct(arr,n);
    return 0;
}


Java




/* Java program to print all distinct elements of a given array */
import java.util.*;
 
class Main
{
    // This function prints all distinct elements
    static void printDistinct(int arr[])
    {
        // Creates an empty hashset
        HashSet<Integer> set = new HashSet<>();
 
        // Traverse the input array
        for (int i=0; i<arr.length; i++)
        {
            // If not present, then put it in hashtable and print it
            if (!set.contains(arr[i]))
            {
                set.add(arr[i]);
                System.out.print(arr[i] + " ");
            }
        }
    }
 
    // Driver method to test above method
    public static void main (String[] args)
    {
        int arr[] = {10, 5, 3, 4, 3, 5, 6};
        printDistinct(arr);
    }
}


Python3




# Python3 program to print all distinct elements
# of a given array
 
# This function prints all distinct elements
def printDistinct(arr, n):
     
    # Creates an empty hashset
    s = dict();
 
    # Traverse the input array
    for i in range(n):
         
        # If not present, then put it in
        # hashtable and print it
        if (arr[i] not in s.keys()):
            s[arr[i]] = arr[i];
            print(arr[i], end = " ");
  
# Driver Code
arr = [10, 5, 3, 4, 3, 5, 6];
n = 7;
printDistinct(arr, n);
 
# This code is contributed by Princi Singh


C#




// C# program to print all distinct
// elements of a given array
using System;
using System.Collections.Generic;
 
class GFG
{
// This function prints all
// distinct elements
public static void printDistinct(int[] arr)
{
    // Creates an empty hashset
    HashSet<int> set = new HashSet<int>();
 
    // Traverse the input array
    for (int i = 0; i < arr.Length; i++)
    {
        // If not present, then put it
        // in hashtable and print it
        if (!set.Contains(arr[i]))
        {
            set.Add(arr[i]);
            Console.Write(arr[i] + " ");
        }
    }
}
 
// Driver Code
public static void Main(string[] args)
{
    int[] arr = new int[] {10, 5, 3, 4, 3, 5, 6};
    printDistinct(arr);
}
}
 
// This code is contributed by Shrikant13


Javascript




<script>
 
// Javascript program to print all distinct elements of a given array
 
    // This function prints all distinct elements
    function printDistinct(arr)
    {
        // Creates an empty hashset
        let set = new Set();
  
        // Traverse the input array
        for (let i=0; i<arr.length; i++)
        {
            // If not present, then put it in hashtable and print it
            if (!set.has(arr[i]))
            {
                set.add(arr[i]);
                document.write(arr[i] + " ");
            }
        }
    }
 
// Driver program
 
      let arr = [10, 5, 3, 4, 3, 5, 6];
        printDistinct(arr);
       
</script>


Output

10 5 3 4 6 




Time Complexity: O(n).
Auxiliary Space: O(n)



Previous Article
Next Article

Similar Reads

Print all unique digits present in concatenation of all array elements in the order of their occurrence
Given an array arr[] consisting of N integers, the task is to print all unique digits of the number formed by concatenating all array elements in the order of their occurrence after excluding leading zeroes. Examples: Input: arr[] = {122, 474, 612, 932}Output: 7 6 9 3Explanation:The number formed by concatenating array elements is “122474612932”.Un
10 min read
Subsequence pair from given Array having all unique and all same elements respectively
Given an array arr[] of N integers, the task is to choose the two subsequences of equal lengths such that the first subsequence must have all the unique elements and the second subsequence must have all the same elements. Print the maximum length of the subsequence pair. Examples: Input: arr[] = {1, 2, 3, 1, 2, 3, 3, 3} Output: 3 Explanation: The f
6 min read
Length of array pair formed where one contains all distinct elements and other all same elements
Given an array arr[], the task is to determine the maximum possible size of two arrays of the same size that can be created using the given array elements, such that in one array all the elements are distinct and in the other, all elements are the same. Note: It is not mandatory to use all the elements of the given array to build the two arrays. Ex
6 min read
Print all unique elements present in a sorted array
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 4Explanation: Since 1, 2, 5 are occurring more than once in the array, the distinct elements are 3 and
5 min read
k-th distinct (or non-repeating) element among unique elements in an array.
Given an integer array, print k-th distinct element in an array. The given array may contain duplicates and the output should print k-th element among all unique elements. If k is more than number of distinct elements, print -1.Examples : Input : arr[] = {1, 2, 1, 3, 4, 2}, k = 2 Output : 4 First non-repeating element is 3 Second non-repeating elem
9 min read
Count Distinct ( Unique ) elements in an array
Given an array arr[] of length N, The task is to count all distinct elements in arr[]. Examples:  Input: arr[] = {10, 20, 20, 10, 30, 10}Output: 3Explanation: There are three distinct elements 10, 20, and 30. Input: arr[] = {10, 20, 20, 10, 20}Output: 2 Naïve Approach: Create a count variable and run two loops, one with counter i from 0 to N-1 to t
15 min read
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 "geek" is 2. The frequency of the string "ab" is 1.
15+ min read
Find the lexicographically largest array containing all distinct elements from each prefix of the given array
Given an array arr[] of length N. The task is to find a lexicographically largest array res[] of the same length such that each prefix of res[] includes all distinct elements present in the corresponding prefix of array arr[]. Examples: Input: N = 6, arr[] = {2, 5, 3, 2, 6, 5}Output: res[] = {2, 5, 3, 6, 6, 6}Explanation: This can be verified that
7 min read
Queries to print count of distinct array elements after replacing element at index P by a given element
Given an array arr[] consisting of N integers and 2D array queries[][] consisting of Q queries of the form {p, x}, the task for each query is to replace the element at position p with x and print the count of distinct elements present in the array. Examples: Input: Q = 3, arr[] = {2, 2, 5, 5, 4, 6, 3}, queries[][] = {{1, 7}, {6, 8}, {7, 2}}Output:
14 min read
Print all distinct integers that can be formed by K numbers from a given array of N numbers
Given an array of N elements and an integer K, print all the distinct integers which can be formed by choosing K numbers from the given N numbers. A number from an array can be chosen any number of times. Examples: Input: k = 2, a[] = {3, 8, 17, 5} Output: The 10 distinct integers are: 6 8 10 11 13 16 20 22 25 34 The 2 elements chosen are: 3+3 = 6,
7 min read
Print all distinct strings from a given array
Given an array of strings arr[] of size N, the task is to print all the distinct strings present in the given array. Examples: Input: arr[] = { "Geeks", "For", "Geeks", "Code", "Coder" } Output: Coder Code Geeks For Explanation: Since all the strings in the array are distinct, the required output is Coder Code Geeks For. Input: arr[] = { "Good", "G
5 min read
Print all unique paths from given source to destination in a Matrix moving only down or right
Given a 2-D array mat[][], a source ‘s’ and a destination ‘d’, print all unique paths from given ‘s’ to ‘d’. From each cell, you can either move only to the right or down. Examples: Input: mat[][] = {{1, 2, 3}, {4, 5, 6}}, s[] = {0, 0}, d[]={1, 2}Output: 1 4 5 61 2 5 61 2 3 6 Input: mat[][] = {{1, 2}, {3, 4}}, s[] = {0, 1}, d[] = {1, 1}Output: 2 4
6 min read
Maximize count of unique array elements by incrementing array elements by K
Given an array arr[] consisting of N integers and an integer K, the task is to find the maximum number of unique elements possible by increasing any array element by K only once. Examples: Input: arr[] = {0, 2, 4, 3, 4}, K = 1Output: 5Explanation:Increase arr[2] ( = 4) by K ( = 1). Therefore, new array is {0, 2, 4, 3, 5} which has 5 unique elements
8 min read
Find Sum of all unique sub-array sum for a given array.
Given an array of n-positive elements. The sub-array sum is defined as the sum of all elements of a particular sub-array, the task is to find the sum of all unique sub-array sum. Note: Unique Sub-array sum means no other sub-array will have the same sum value. Examples: Input : arr[] = {3, 4, 5} Output : 40 Explanation: All possible unique sub-arra
10 min read
Find all unique pairs of maximum and second maximum elements over all sub-arrays in O(NlogN)
Let [Tex](a, b) [/Tex]represent the ordered pair of the second maximum and the maximum element of an array respectively. We need to find all such unique pairs overall contiguous sub-arrays of a given array. Examples: Input: Arr = [ 1, 2, 3, 4, 5 ] Output: (1, 2) (2, 3) (3, 4) (4, 5) Input: Arr = [ 1, 1, 2 ] Output: (1, 1) (1, 2) Input: Arr = [ 1, 2
13 min read
Print a number strictly less than a given number such that all its digits are distinct.
Given a positive number n, print a number less than n such that all its digits are distinct.Examples: Input : 1134 Output : 1098 1098 is the largest number smaller than 1134 such that all digits are distinct. Input : 4559 Output : 4539 The problem can easily be solved by using counting. Firstly, loop through numbers less than n and for each number
6 min read
Print all distinct permutations of a given string with duplicates
Given a string that may contain duplicates, write a function to print all permutations of given string such that no permutation is repeated in output.Examples: Input: str[] = "AB" Output: AB BA Input: str[] = "AA" Output: AA Input: str[] = "ABC" Output: ABC ACB BAC BCA CBA CAB Input: str[] = "ABA" Output: ABA AAB BAA Input: str[] = "ABCA" Output: A
15 min read
Count all distinct pairs of repeating elements from the array for every array element
Given an array arr[] of N integers. For each element in the array, the task is to count the possible pairs (i, j), excluding the current element, such that i &lt; j and arr[i] = arr[j]. Examples: Input: arr[] = {1, 1, 2, 1, 2}Output: 2 2 3 2 3Explanation:For index 1, remaining elements after excluding current element are [1, 2, 1, 2]. So the count
7 min read
Print sorted distinct elements of array
Given an array that might contain duplicates, print all distinct elements in sorted order. Examples: Input : 1, 3, 2, 2, 1Output : 1 2 3Input : 1, 1, 1, 2, 2, 3Output : 1 2 3The simple Solution is to sort the array first, then traverse the array and print only first occurrences of elements. Algorithm: Sort the given array in non-descending order. T
6 min read
For all Array elements find Product of Sum of all smaller and Sum of all greater elements
Given an array arr[] of integers of length N, the task is to find the product of the sum of all the numbers larger than that number with the sum of all the numbers less than that number for each number in the array. Examples: Input: arr[] = {8, 4, 9, 3}, N = 4Output:- 63, 51, 0, 0Explanation:For first number 8: Sum of elements smaller than this is
15 min read
Print All Distinct Permutations of an Array
Given an array nums[] of size N, the task is to print all distinct permutations of the given array. Input: nums[] = { 1, 2, 2 }Output: 1 2 22 1 22 2 1 Input: nums[] = { 1, 1 }Output: 1 1 Recommended ProblemAll Unique Permutations of an arraySolve Problem Traverse the array.Generate permutations of an array.Set an order of selection among duplicate
8 min read
Maximize count of unique elements in Array by changing elements to negative
Given array arr containing N integers. the task is to find the maximum number of unique elements in the array if each element in the array can be changed to its negative i.e. X can be changed to -X in the array. Example: Input: arr[] = {-1, 3, 2, 3, 2}Output: 5Explanation: Change one 2 to -2 and another 3 to -3 to get the arr[]={-1, 3, 2, -3, -2},
5 min read
Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2
Given an array arr[] containing 2*N+2 positive numbers, out of which 2*N numbers exist in pairs whereas the other two number occur exactly once and are distinct. Find the other two numbers. Return in increasing order. Example: Input: N = 2, arr[] = {1, 2, 3, 2, 1, 4}Output:3 4 Explanation: 3 and 4 occur exactly once. Input: N = 1, arr[] = {2, 1, 3,
9 min read
Find sum of all unique elements in the array for K queries
Given an arrays arr[] in which initially all elements are 0 and another array Q[][] containing K queries where every query represents a range [L, R], the task is to add 1 to each subarrays where each subarray is defined by the range [L, R], and return sum of all unique elements.Note: One-based indexing is used in the Q[][] array to signify the rang
8 min read
Unique element in an array where all elements occur K times except one | Set 2
Given an array arr[] where every element occurs K times except one element which occurs only once, the task is to find that unique element.Examples: Input: arr[] = {12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7}, k = 3 Output: 7 Explanation: 7 is the only element which occurs once while others occurs k times.Input: arr[] = {12, 12, 2, 2, 3}, k = 2 Outpu
13 min read
Unique element in an array where all elements occur k times except one
Given an array that contains all elements occurring k times, but one occurs only once. Find that unique element.Examples: Input : arr[] = {6, 2, 5, 2, 2, 6, 6} k = 3Output : 5Explanation: Every element appears 3 times accept 5. Input : arr[] = {2, 2, 2, 10, 2} k = 4Output: 10Explanation: Every element appears 4 times accept 10. Recommended Practice
13 min read
Count all N-length arrays made up of distinct consecutive elements whose first and last elements are equal
Given two integers M and N, the task is to find the number of N-length arrays possible having non-equal adjacent elements lying in the range [1, M] having elements at first and last indices equal. Examples: Input: N = 3, M = 3Output: 6Explanation:The possible arrays are {1, 2, 1}, {1, 3, 1}, {2, 1, 2}, {2, 3, 2}, {3, 1, 3}, {3, 2, 3}. Input: N = 5,
7 min read
Count distinct sequences obtained by replacing all elements of subarrays having equal first and last elements with the first element any number of times
Given an array arr[] consisting of N integers, the task is to find the number of different sequences that can be formed after performing the below operation on the given array arr[] any number of times. Choose two indices i and j such that arr[i] is equal to arr[j] and update all the elements in the range [i, j] in the array to arr[i]. Examples: In
7 min read
Print first K distinct Moran numbers from a given array
Given an array arr[] consisting of N distinct positive integers, the task is to print the first K distinct Moran Numbers from the given array. A number N is a Moran number if N divided by the sum of its digits gives a prime number. Examples: 18, 21, 27, 42, 45 Examples: Input: arr[] = {192, 21, 18, 138, 27, 42, 45}, K = 4 Output: 21, 27, 42, 45 Exp
11 min read
Print all numbers less than N with at-most 2 unique digits
Given a number N(less than 10^9). The task is to print all the numbers less than N which are having a maximum of 2 unique digits. Note: Number such as 100, 111, 101 are valid as the number of unique digits are at most 2 but 123 is invalid as it has 3 unique digits.Examples: Input: N = 12 Output: The numbers are: 1 2 3 4 5 6 7 8 9 10 11Input: N = 15
6 min read
Article Tags :
Practice Tags :