Challenge 1: Single Number

In this lesson, every element appears twice except one element. Try to come up with a process to solve this. Use your XOR skills to achieve this.

Introduction

In this question, every element appears twice except one element, which is our answer.

Let’s see how to achieve this using the XOR operator.

Problem statement

We need to write a program that finds the element that is not repeated.

Input: nums = { 4, 1, 2, 9, 1, 4, 2 }
 
Output: 9

Explanation: Except for 9, all elements are repeated.

Assume n is non-negative.

Hint: Use the ^ operator to achieve this.

Solution

We solve this using naive, and then we move to solve it in a more optimal way.

Brute force

This is a naive approach. We traverse the entire array twice to achieve this, which is not optimal.

Algorithm

Iterate the elements using two for loops and find the one that is not repeating.

Complexity analysis

Time Complexity: O(n2n^{2})

Space Complexity: ...

Access this course and 1400+ top-rated courses and projects.