×

Finding Odd Occurrence of a Number in Java

In this tutorial, we will learn how to find the odd occurrence of a number through a java program.

Let us consider an array of non-negative integers. Here, except for one number, the rest all the numbers occur an odd number of times. The goal is to fetch that number that is occurring an odd number of times in an array

Example 1:

Input: arr[] = {17, 24, 35, 24, 35, 17, 35, 59, 38, 59, 96, 35, 38, 96, 35}

Output: 35

Explanation: Except for 35, all the other numbers are occurring an even number of times. We can see in the array arr[] that the number 35 occurs 5 times which is odd.

Example 2:

Input: arr[] = {54, 27, 9, 27, 45, 9, 34, 7, 34, 7, 2, 54, 45 }

Output: 2

Explanation: Except for 2 all the other numbers are occurring an even number of times. We can see in the array arr[] that the number 2 occurs 1 odd time.

Example 3:

Input: arr[] = {94, 88 , 19, 88 , 1512 , 15, 19, 34, 17, 34, 17, 12, 94, 15 }

Output: 15

Explanation: Except for 15 all the other numbers are occurring an even number of times. We can see in the array arr[] that the number 15 occurs 3 times which is odd.

Simple Approach

The goal of our program is to get the count of a number that occurs an odd number of times in an array. So, we can do it by using two loops. One loop is to be used for picking the number and the other one is to count the frequency of that no. If the count of frequency comes even, we will discard the number therein and if it’s odd we will return it.

Implementation

public class OddOccurrence  
{  


public int OddOccurrence(int arr[], int size)  
{  


// outer loop that runs for each element
for (int i = 0; i < size; i++)  
{  


// to count the number of  
// times a number occurs in the array  
int Freq = 0;  


for (int j = 0; j < size; j++)  
{  
    if(arr[i] == arr[j])  
    {  
        // stores the frequency of the nos.
        Freq = Freq + 1;      
    }  
}  
 //checking odd occurrence of the no. 
if(Freq % 2 == 1)  
{  
return  arr[i];  
}  


}  
return -1;  
}  


// main method  
public static void main(String argvs[])  
{  


// creation of an object of the class named OddOccurrence  
OddOccurrence obj = new OddOccurrence();  


// input array  
int arr[] = {27, 54, 215, 54, 54, 27, 215, 9, 81, 9, 6, 81, 6};  


// calculating the size of the array  
int size = arr.length;  




// showing the result  
System.out.println("The input array is ");  


for(int i = 0; i < arr.length; i++)  
{  
System.out.print(arr[i] + " ");      
}  
System.out.println();  
int result = obj.OddOccurrence(arr, size);  


System.out.println("The number whose occurrence is odd : " + result);  


System.out.println();  


// input array  
int arr2[] = {41, 23, 19, 23, 41, 19, 41, 7, 41, 7, 41};  


// computing the size of the array  
size = arr2.length;  


// displaying the outcome  
System.out.println("The input array: ");  


for(int i = 0; i < arr2.length; i++)  
{  
System.out.print(arr2[i] + " ");      
}  
System.out.println();  
result = obj.OddOccurrence(arr2, size);  


System.out.println("The number whose occurrence is odd is: " + result);  


// input array  
int arr3[] = {61, 43, 19, 43, 81, 19, 81, 7, 79, 7, 79, 71};  


// calculating the size of the array  
size = arr3.length;  


// displaying the outcome  
System.out.println("The input array: ");  


for(int i = 0; i < arr3.length; i++)  
{  
System.out.print(arr3[i] + " ");      
}  
System.out.println();  
result = obj.OddOccurrence(arr3, size);  


System.out.println("The number whose occurrence is odd is: " + result); 


}  
}  

Output:

Finding Odd Occurrence of a Number in Java

Explanation: The program uses 2 nested loops.So, the time complexity program is O(n2) where n refers to the total number of elements.

Space complexity here is O(1).

Approach 2:

Using Array

One can take an array into account to store the frequency of the occurrence of the elements. Then, one can easily find out the numbers whose frequency of occurence is odd.

Implementation:

public class OddOccurrence1  
{  


// method to find the maximum element  
public int findMax(int arr[], int size)  
{  
int res = 0;  
for(int i = 0 ; i < size; i++)  
{  
if(res < arr[i])  
{  
res = arr[i];  
}  
}  


return res;  
}  


public int OddOccurrence(int arr[], int size)  
{  
int res = findMax(arr, size);  


// to store the counting of elements  
int storeFreq[] = new int[res + 1];  


int leng = res + 1;  




for(int j = 0; j < size; j++)  
{  
storeFreq[arr[j]] = storeFreq[arr[j]] + 1;  
}  


for(int j1 = 0; j1 < leng; j1++)  
{  
if(storeFreq[j1] % 2 == 1)  
{  
return j1;  
}  






}  
return -1;  


}  




// main method  
public static void main(String argvs[])  
{  


// creation of an object of the class named OddOccurrence1  
OddOccurrence1 obj = new OddOccurrence1();  


// input array  
int arr[] = {17, 24, 35, 44, 36, 35, 17, 35, 91, 48, 91, 36, 48, 36, 36};  


// calculating the size of the array  
int size = arr.length;  




// showing the result  
System.out.println("The input array: ");  


for(int i = 0; i < arr.length; i++)  
{  
System.out.print(arr[i] + " ");      
}  
System.out.println();  
int res = obj.OddOccurrence(arr, size);  


System.out.println("The number that occurred an odd number of times is: " + res);  


System.out.println();  


// input array  
int arr1[] = {24, 93, 77, 19, 93, 24, 19, 24, 77, 24, 77, 24, 24};  


// calculating the size of the array  
size = arr1.length;  


// displaying the result  
System.out.println("The input array: ");  


for(int i = 0; i < arr1.length; i++)  
{  
System.out.print(arr1[i] + " ");      
}  
System.out.println();  
res = obj.OddOccurrence(arr1, size);  


System.out.println("The number that occurred an odd number of times is: " + res);  


}  
}  

Output:

Finding Odd Occurrence of a Number in Java

Explanation: The program uses 3 loops but they are not nested So, the time complexity program is O(n) where n refers to the total number of elements.

The space complexity here is more than the above approach. Spaces here are getting wasted too.

To reduce the space complexity, we can use another approach.

Approach 3:

Using HashMap

To store the frequency of the elements in an array, one can use the hash map and later can check which number has an odd frequency of its occurrence.

Implementation:

// import statement required to use HashMap
import java.util.HashMap;  


public class OddOccurrence2  
{  


public int OddOccurrence2(int arr[], int size)  
{  


// In the hash map, the key will serve as the element and the value will serve as the
// frequency of occurrence of the elements.  




HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();   


// For every number beginning from 1 till n, calculate the sum of digits  


for (int i = 0; i < size; i++)  
{  


if(hm.containsKey(arr[i]))  
{  
int countFreq = hm.get(arr[i]);  


// If the element is present in the hash map then  
// increase the frequency count of the occurrence of that element by 1.  
hm.put(arr[i], countFreq + 1);   
}  
else  
{  
// if the element does not lie in the hash map then put  
// that element in the hash map and initialize the  count of the frequency    
// by one.  
hm.put(arr[i], 1);  
}  
}  


// finding out the odd occurrence of each of the element  
// in the hash map   
for(Integer j :hm.keySet())  
{  
    if(hm.get(j) % 2 != 0)  
    {  
        return j;  
    }  
}  


return -1;  


}  




// main method  
public static void main(String argvs[])  
{  


// creation of an object of the class named OddOccurrence2  
OddOccurrence2 obj = new OddOccurrence2();  


// input array  
int arr1[] = {15, 77, 94, 15, 94, 15, 77, 15, 19, 18, 19, 26, 18, 15, 26};  


// calculating the length of the array  
int size = arr1.length;  




// showing the output  
System.out.println("The input array is ");  


for(int i = 0; i < arr1.length; i++)  
{  
System.out.print(arr1[i] + " ");      
}  
System.out.println();  
int res = obj.OddOccurrence2(arr1, size);  


System.out.println("The number that occurred an odd number of times is: " + res);  


System.out.println();  


// input array  
int arr2[] = {14, 43, 59, 43, 14, 59, 14, 37, 14, 37, 14};  


// calculating the size of the array  
size = arr2.length;  


// showing the output
System.out.println(" The input array is ");  


for(int j = 0; j < arr2.length; j++)  
{  
System.out.print(arr2[j] + " ");      
}  
System.out.println();  
res = obj.OddOccurrence2(arr2, size);  


System.out.println("The number that occurred an odd number of times is: " + res);  


}  
}  

Output:

Finding Odd Occurrence of a Number in Java

Explanation: The time complexity of the program remains O(n) as no nested loops are used. The space complexity is also O(n). However, some spaces are being wasted here as well.

We can further optimize our program and get a better result.

We can use the Bitwise XOR method which will yield space complexity as O(1).

But in this tutorial, we will restrict our discussion to here only.


Related Topics

The Diamond Operator in Java 7

The Diamond operator is a comparatively recent Java operator originally developed in JDK 7 to enhance type identification and eliminate boilerplate Java code. The Diamond operator is characterized by a...

2 minutes read.

Java Enum Keyword

Definition: A data type in Java called Enum has a respect to supply of constants. The weekdays (SUN, MON, TUE, WED, THU, FRI, and SAT), directions (NORTH, SOUTH, EAST, and WEST),...

4 minutes read.

Stack vs Heap in Java

In Java, whenever we declare an object or create a variable, whether it is an instance variable, local variable, or static variable, a certain memory is used to store the...

4 minutes read.

Split the Number String into Primes in Java

Given is a string that only contains digits and serves to represent a number. Our goal is to split the string of numbers in a way that ensures each segment...

2 minutes read.

Short Circuit Logical Operators in Java

When there are two or more relational expressions in a decision-making statement, logical operators are utilized to combine them. The logical operators short circuit and not-short circuit fall into two...

5 minutes read.

Java Extends vs Implements

Java: We known that the java is a pure object oriented programming language. Java programming language consists of many features such as portable, plat form independence, secured, robust, simple, architecture neutral,...

4 minutes read.

How to add 4 Hours to the Current Date in Java?

In this tutorial, we will learn how to add 4 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

GCD Program in Java

GCD Program in Java The GCD program in Java outputs the GCD of the given numbers. In mathematics, Greatest Common Divisor (GCD), Greatest Common Factor or Highest Common Factor (HCF) of...

14 minutes read.

String Matches in Java

Firstly we have to know something about String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java...

3 minutes read.

Java Command Line Argument

Command-line arguments are passed to the main() method when we want to pass information into a program during runtime. It is the information that directly follows the program’s name on the...

1 minute read.

Java Wrapper classes

Java Wrapper classes A wrapper class is a class whose object contains a primitive data type; moreover it provides a way to use primitive data type (int, boolean, etc.) as objects. Wrapper...

2 minutes read.

Java Boolean Keyword

Boolean keyword In java programming language we basically have two types of primitive data types, Boolean and Numeric (integer and floating-point data types). In this article we are going to learn...

4 minutes read.

Java Enum vs Class

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four integrators named Club, Diamond,...

7 minutes read.

Java File Extension

A computer file's suffix is called its file extension. It is easily recognized since it appears immediately after a period (.) in the file name. Consider the file Demo.java as an...

3 minutes read.

Java Program to Sort an Array of 0's, 1's, and 2’s | Dutch National Flag Problem in Java

The famed Dutch computer programmer Edsger Dijkstra's Dutch Nation Flag (DNF) challenge ranks among the most well-known programming challenges. The Dutch tricolor flag, comprising red, white, and blue, is the...

3 minutes read.

Hamming Code in Java

In a computer network, hamming code is a unique set of error-correction codes. It is mostly utilised in computer graphics for mistake detection and correction during data transmission from sender...

8 minutes read.

Java String lastIndexOf() method

Java String lastIndexOf() method returns last index of character or substring in a String. Syntax: Method Description int lastIndexOf(int ch)It returns last index position for the given char valueint lastIndexOf(int ch, int...

2 minutes read.

Intersection Point of two linked list in Java

In this article, you will be very well acknowledged about how to achieve the intersection point of two linked list in Java. There are several approaches to obtain. Surely each...

8 minutes read.

Sylvester Sequence in Java

A Sylvester Sequence is a series of numbers in which each term is the sum of the terms before it plus 1. The sequence's first two terms are 2 and...

3 minutes read.

Java String toUpperCase() methods

Java String toUpperCase() method is used to convert all the characters of the String into upper case. Syntax public String toUpperCase() public String toUpperCase(Locale locale) Returns It returns upper case String. Java String toUpperCase() Example 1: public...

1 minute read.