Article start
DSA Course: Interview Patterns and Problem Solving
Module 14: Bit Manipulation

XOR From 1 to N: Modulo Cycle Pattern

Compute cumulative XOR using the repeating four-value cycle.

May 29, 2026·26

Learning Outcome

After this lesson, you should be able to recognize the repeating pattern in cumulative XOR from 1 to n.

Problem Statement

Given n, return the XOR of all integers from 1 to n.

InputOutputWhy
n = 1011The cumulative XOR pattern repeats every 4 values, and 10 mod 4 equals 2, so the answer is n + 1.

Brute Force Approach

Loop from 1 to n and XOR every value. This works but costs O(n).

Optimized Approach

Use the known cycle: n mod 4 equals 0 -> n, 1 -> 1, 2 -> n + 1, and 3 -> 0.

Exact Pseudocode

remainder = n % 4
if remainder == 0:
  return n
if remainder == 1:
  return 1
if remainder == 2:
  return n + 1
return 0

Reference Code

class Solution:
    def xorTillN(self, n):
        remainder = n % 4
        if remainder == 0:
            return n
        if remainder == 1:
            return 1
        if remainder == 2:
            return n + 1
        return 0

Sample Dry Run

StepStateResult
Observe cyclexor(1)=1, xor(2)=3, xor(3)=0, xor(4)=4Pattern repeats every 4
n = 1010 mod 4 = 2Use n + 1 case
Return10 + 1answer = 11

Complexity

MeasureValueReason
TimeO(1)The answer comes from one modulo operation and constant checks.
SpaceO(1)No extra storage is used.

Edge Cases

  • If n = 0 and the range is empty, return 0.
  • The case n mod 4 = 2 returns n + 1.
  • Do not confuse cumulative XOR with sum.

Interview Checklist

  • Memorize or derive the four-case cycle.
  • Use n % 4 to choose the answer.
  • Handle n = 0 if the prompt allows it.

FAQs

Why does the cycle repeat every 4?

XORing consecutive integers produces a stable four-case pattern based on the low two bits.

Can this answer range XOR queries?

Yes. XOR from L to R can be built from xor(1..R) xor xor(1..L-1).

What is the core pattern?

Modulo-4 XOR cycle.

Test your knowledge

Take a quick quiz based on this chapter.

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.