Solved the "Single Number" problem using XOR. Learned about bitwise operations and micro-optimisation.

Today I learned something interesting, I learnt to solve the classic “Single Number” problem: given an array where every element appears twice except one, find the one that appears only once. I initialise result = 0 and XOR it with each number in the array — because a ^ a = 0 and a ^ 0 = a, all duplicates cancel out, leaving the unique number. For example, with [4,2,1,2,4], the process goes: 0 ^ 4 = 4   4 ^ 2 = 6   6 ^ 1 = 7   7 ^ 2 = 5   5 ^ 4 = 1  — and the answer is 1.  What I learned: 1) Bitwise operations (XOR) can give very efficient solutions. 2) Always look at the constraints: “linear time” + “constant space” guided this decision. Even when an approach works, micro-optimisation (loop style, engine behaviour) still affects performance. I’m excited to keep pushing my problem-solving skills and discovering more of these clever tricks. If you’ve got a favourite algorithm or bitwise trick, I’d love to hear it! 💬 #coding #algorithms #javascript #programming #leetcode #learning

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories