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 Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Lex program to check whether input number is odd or even
Next article icon

C/C++ Program to Find the Number Occurring Odd Number of Times

Last Updated : 13 Jul, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of positive integers that occur even number of times, except one number, which occurs odd number of times. The task is to find this odd number of times occurring number.

Examples :  

Input : arr = {1, 2, 3, 2, 3, 1, 3}  Output : 3    Input : arr = {5, 7, 2, 7, 5, 2, 5}  Output : 5

Naive Approach: A Simple Solution is to run two nested loops. The outer loop picks all elements one by one and inner loop counts the number of occurrences of the element picked by outer loop. 

Implementation:

C++

  // C++ program to find the element  // occurring odd number of times  #include <bits/stdc++.h>  using namespace std;    // Function to find the element  // occurring odd number of times  int getOddOccurrence(int arr[], int arr_size)  {      for (int i = 0; i < arr_size; i++) {            int count = 0;            for (int j = 0; j < arr_size; j++) {              if (arr[i] == arr[j])                  count++;          }          if (count % 2 != 0)              return arr[i];      }      return -1;  }    // driver code  int main()  {      int arr[] = { 2, 3, 5, 4, 5, 2,                    4, 3, 5, 2, 4, 4, 2 };      int n = sizeof(arr) / sizeof(arr[0]);        // Function calling      cout << getOddOccurrence(arr, n);        return 0;  }  

C

// C program to find the element  // occurring odd number of times  #include <stdio.h>     // Function to find the element  // occurring odd number of times  int getOddOccurrence(int arr[], int arr_size)  {      for(int i = 0; i < arr_size; i++)      {          int count = 0;            for(int j = 0; j < arr_size; j++)           {              if (arr[i] == arr[j])                  count++;          }          if (count % 2 != 0)              return arr[i];      }      return -1;  }    // Driver code  int main()  {      int arr[] = { 2, 3, 5, 4, 5, 2,                    4, 3, 5, 2, 4, 4, 2 };      int n = sizeof(arr) / sizeof(arr[0]);        // Function calling      printf("%d",getOddOccurrence(arr, n));            return 0;  }    // This code is contributed by rbbansal
Output: 
5

 

Time complexity: O(N2) 
Auxiliary space: O(1)

Better Approach: A Better Solution is to use Hashing. Use array elements as key and their counts as value. Create an empty hash table. One by one traverse the given array elements and store counts. Time complexity of this solution is O(n). But it requires extra space for hashing.
Time complexity: O(N) 
Auxiliary space: O(N)

Efficient Approach: The Best Solution is to do bitwise XOR of all the elements. XOR of all elements gives us odd occurring element. Please note that XOR of two elements is 0 if both elements are same and XOR of a number x with 0 is x.

Below is the implementation of the above approach.  

C++

  // C++ program to find the element  // occurring odd number of times  #include <bits/stdc++.h>  using namespace std;    // Function to find element occurring  // odd number of times  int getOddOccurrence(int ar[], int ar_size)  {      int res = 0;      for (int i = 0; i < ar_size; i++)          res = res ^ ar[i];        return res;  }    /* Driver function to test above function */  int main()  {      int ar[] = { 2, 3, 5, 4, 5,                   2, 4, 3, 5, 2,                   4, 4, 2 };      int n = sizeof(ar) / sizeof(ar[0]);        // Function calling      cout << getOddOccurrence(ar, n);        return 0;  }  

C

  // C program to find the element  // occurring odd number of times  #include <stdio.h>    // Function to find element occurring  // odd number of times  int getOddOccurrence(int ar[], int ar_size)  {      int res = 0;      for (int i = 0; i < ar_size; i++)          res = res ^ ar[i];        return res;  }    /* Driver function to test above function */  int main()  {      int ar[] = { 2, 3, 5, 4, 5,                   2, 4, 3, 5, 2,                   4, 4, 2 };      int n = sizeof(ar) / sizeof(ar[0]);        // Function calling      printf("%d", getOddOccurrence(ar, n));      return 0;  }  
Output: 
5

 

Time complexity: O(N) 
Auxiliary space: O(1)
Please refer complete article on Find the Number Occurring Odd Number of Times for more details!
 



Next Article
Lex program to check whether input number is odd or even
author
kartik
Improve
Article Tags :
  • Arrays
  • C Programs
  • C++ Programs
  • DSA
  • Hash
  • Bitwise-XOR
Practice Tags :
  • Arrays
  • Hash

Similar Reads

  • C Program for Find sum of odd factors of a number
    Write a C program for a given number n, the task is to find the odd factor sum. Examples: Input : n = 30Output : 24Explanation: Odd dividers sum 1 + 3 + 5 + 15 = 24 Input : 18Output : 13Explanation: Odd dividers sum 1 + 3 + 9 = 13 C Program for Find sum of odd factors of a number using Prime Factori
    3 min read
  • C++ Program to Check Whether Number is Even or Odd
    A number is even if it is completely divisible by 2 and it is odd if it is not completely divisible by 2. In this article, we will learn how to check whether a number is even or odd in C++. Examples Input: n = 11Output: OddExplanation: Since 11 is not completely divisible by 2, it is an odd number.
    4 min read
  • C Program to Check for Odd or Even Number
    Write a C program to check whether the given number is an odd number or an even number. A number that is completely divisible by 2 is an even number and a number that is not completely divisible by 2 leaving a non-zero remainder is an odd number. Example Input: N = 4Output: EvenExplanation: 4 is div
    4 min read
  • C++ Program to find sum of even factors of a number
    Given a number n, the task is to find the even factor sum of a number. Examples: Input : 30 Output : 48 Even dividers sum 2 + 6 + 10 + 30 = 48 Input : 18 Output : 26 Even dividers sum 2 + 6 + 18 = 26 Let p1, p2, … pk be prime factors of n. Let a1, a2, .. ak be highest powers of p1, p2, .. pk respect
    3 min read
  • Lex program to check whether input number is odd or even
    Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. The commands for executing the lex program are: lex abc.l (abc is the file name) gcc lex.yy.c -ll ./a.ou
    1 min read
  • C Program for Number of elements with odd factors in given range
    Given a range [n, m], find the number of elements that have odd number of factors in the given range (n and m inclusive). Examples: Input : n = 5, m = 100 Output : 8 The numbers with odd factors are 9, 16, 25, 36, 49, 64, 81 and 100 Input : n = 8, m = 65 Output : 6 Input : n = 10, m = 23500 Output :
    2 min read
  • C++ Program to Rotate all odd numbers right and all even numbers left in an Array of 1 to N
    Given a permutation arrays A[] consisting of N numbers in range [1, N], the task is to left rotate all the even numbers and right rotate all the odd numbers of the permutation and print the updated permutation. Note: N is always even.Examples:  Input: A = {1, 2, 3, 4, 5, 6, 7, 8} Output: {7, 4, 1, 6
    2 min read
  • Count Numbers with N digits which consists of odd number of 0's
    We are given a number N. The task is to find the count of numbers which have N digits and odd number of zeroes. Note: The number can have preceding 0's. Examples: Input : N = 2 Output : Count = 18 Input : N = 3 Output : Count = 244 Suppose a number with N digits which contains only single zero. So t
    4 min read
  • C++ Program to Print Even Numbers in an Array
    Given an array of numbers, the task is to print all the even elements of the array. Let us understand it with few examples mentioned below. Example: Input: num1 = [2,7,6,5,4] Output: 2, 6, 4 Input: num2 = [1,4,7,8,3] Output: 4, 81. Using for loop Approach: Iterate each element in the given using for
    5 min read
  • C++ Program To Check Whether The Length Of Given Linked List Is Even Or Odd
    Given a linked list, the task is to make a function which checks whether the length of the linked list is even or odd. Examples: Input : 1->2->3->4->NULL Output : Even Input : 1->2->3->4->5->NULL Output : OddRecommended: Please solve it on "PRACTICE" first, before moving o
    3 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