Find a Single Occurrence Number in an Array, Given all other numbers occurred twice.
💻 coding

Find a Single Occurrence Number in an Array, Given all other numbers occurred twice.

1 min read 109 words
1 min read
ShareWhatsAppPost on X
  • 1The algorithm identifies a single occurrence number in an array where all other numbers appear twice.
  • 2It utilizes the XOR operation to achieve linear runtime complexity of O(n).
  • 3The solution requires no extra memory, maintaining a space complexity of O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The algorithm identifies a single occurrence number in an array where all other numbers appear twice."

Find a Single Occurrence Number in an Array, Given all other numbers occurred twice.

You have been given a non-empty array of integers in which every element appears twice except for one. You have to Find that single one.

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

We will use XOR Operation to achieve this goal.

public class SingleNumber {

	public static void main(String[] args) {
		int[] arr = new int[] {12, 4, 36, 10, 12, 36, 4};
		int res = arr[0];
		for(int i=1;i<arr.length;i++) {
			res = res ^ arr[i];
		}
		
		System.out.println(res);

	}

}

Output :

10

Time Complexity of above solution os O(n) and Space Complexity is O(1) (i.e no extra space is used)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 20 July 2018 · 1 min read · 109 words

Part of AskGif Blog · coding

You might also like

Find a Single Occurrence Number in an Array, Given all other numbers occurred twice. | AskGif Blog