Go Back

Single Number Problem Walkthrough

Written by Silent Programmer

Problem Description:

Given an array arr[] of positive integers where every element appears even times except for one. Find that number occurring an odd number of times.

Example:

Input: arr[] = [1, 1, 2, 2, 2]
Output: 2
Explanation: In the given array, all elements appear twice except for 2, which appears three times.
Input: arr[] = [8, 8, 7, 7, 6, 6, 1]
Output: 1
Explanation: In the given array, all elements appear twice except for 1, which appears only once.

Solution:

Code Implementation (C++):

            class Solution {
                public:
                  // Function to find the element in the array which occurs only once.
                  int getSingle(vector& arr) {
                      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;
                  }
              };
        

Written with 💌 by Silent Programmer