Unique Color Shirt

CONCEPTS USED:

Hashing

DIFFICULTY LEVEL:

Easy

PROBLEM STATEMENT(SIMPLIFIED):

Given an array A with N integers, find the count of unique integers in the array.

See original problem statement here

For Example:

Input : arr = [3 2 4 1 2 3]

Output : 2

Explanation: only 1 and 4 are unique in the array rest 2, 3 are occurring 2 times.

SOLVING APPROACH:

  1. Learn programming languages online and Initialize a temporary Hash Array for storing the frequency of all the elements in the array.

  2. Traverse the array and keep incrementing the frequency of elements in the Hash Array.

  3. Finally, traverse and find the count of all such unique elements, hence print it.

SOLUTIONS:

#include <stdio.h>

int main()
{
  int n; scanf("%d", &n);
  int arr[n];

  /* hash array for storing frequency of same coloured shirts */
  int hash[1001] = {0};

  //count of unique shirts
  int count = 0;

  /* input the shirt and increment its frequency */
  for(int i=0; i<n; i++){
    scanf("%d", &arr[i]);
    hash[arr[i]]++;
  }

  //count all unique shirts
  for(int i=0; i<n; i++){
    if(hash[arr[i]] == 1)
      count++;
  }
  printf("%d", count);

  return 0;
}
#include <bits/stdc++.h>
using namespace std;

int main()
{
  int n; cin>>n;
  int arr[n];

  /* hash array for storing frequency of same coloured shirts */
  int hash[1001] = {0};

  //count of unique shirts
  int count = 0;

  /* input the shirt and increment its frequency */
  for(int i=0; i<n; i++){
    cin>>arr[i];
    hash[arr[i]]++;
  }

  //count all unique shirts
  for(int i=0; i<n; i++){
    if(hash[arr[i]] == 1)
      count++;
  }
  cout<<count;

  return 0;
}



import java.util.*;
import java.io.*;

public class Main {
  public static void main(String args[]) throws IOException {

    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int arr[] = new int[n];

    /* hash array for storing frequency of same coloured shirts */
    int hash[] = new int[1001];

    //count of unique shirts
    int count = 0;

    /* input the shirt and increment its frequency */
    for(int i=0; i<n; i++){
      arr[i] = sc.nextInt();;
      hash[arr[i]]++;
    }

    //count all unique shirts
    for(int i=0; i<n; i++){
      if(hash[arr[i]] == 1)
        count++;
    }
    System.out.println(count);
  }
}


Space Complexity : O(N), due to additional Hash Array.
Previous post Find the Leader
Next post Unique Array

Leave a Reply

Your email address will not be published. Required fields are marked *