Monday, March 2, 2026

Range Queries - print the number of integers in the given range which satisfy the above condition (Easy)

Index of "Algorithms: Design and Analysis"
<<< Previous    Next >>>

Basic Programming > Bit Manipulation > Basics of Bit Manipulation

Problem

Given Q queries of type L R X, find the count of integers in range [L,R] such that their Xth bit (1-indexed) is ON from the LSB (least significant bit) side.

Input Format:

  • First line contains an integer Q, denoting the number of queries.
  • Next Q lines contains three space-separated integres L R X.

Output Format:

For every query, print the number of integers in [L,R] which satisfy the above condition.

Constraints:

1Q1051LR1051X20

Sample Input
1
2 6 2
Sample Output
3
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation
  • Binary representation of integers in range [2,6] are as follows:-
    • 2 : 10
    • 3 : 11
    • 4 : 100
    • 5 : 101
    • 6 : 110
  • There are three integers with X-th bit ON i.e. 2, 3 and 6.
  • Thus, required answer is 3.


I am learning Data Structures and Algorithms.

I will provide a screenshot of a problem statement. 

Your task is NOT to directly give me the final code solution unless I explicitly ask for it.

Instead, please do the following:

1. First, carefully restate the problem in your own words to confirm correct understanding.
   - If anything is unclear in the screenshot, ask me clarification questions before proceeding.

2. Identify:
   - What category of problem this is (e.g., prefix sum, greedy, DP, two pointers, binary search, graph, etc.)
   - What core DSA concepts are being tested
   - What mathematical observations (if any) are involved
   - What constraints are important and how they affect the approach

3. Explain:
   - What naive/brute-force solution would look like
   - Why that may or may not work under the given constraints
   - What optimization insight is required

4. Clearly explain the key trick or insight needed to solve it.
   - Why does that trick work?
   - What pattern should I remember for future problems?

5. Provide:
   - The time complexity and space complexity of the optimal approach
   - Why it satisfies the constraints

6. If there are multiple valid approaches, compare them.

7. Only after all conceptual explanation, provide clean and correct Python code.

8. Avoid guessing unclear details.
   - If any part of the screenshot is ambiguous, ask me instead of assuming.

Focus on correctness over speed. Be explicit in reasoning.



Great 👍 Let’s go step by step exactly as you requested.


✅ 1. Restating the Problem (Understanding Check)

You are given Q queries.

Each query contains three integers:

Code
L, R, X

For each query, you must count how many integers in the range [L, R] have their X-th bit (1-indexed from the LSB) turned ON.

Important details:

  • Bits are counted from the right (LSB).

  • X is 1-indexed.

    • X = 1 → check the least significant bit

    • X = 2 → second bit from right

  • Constraints:

    • 1Q1051 \le Q \le 10^5

    • 1LR1051 \le L \le R \le 10^5

    • 1X201 \le X \le 20


Example from screenshot:

Query:

Code
L = 2, R = 6, X = 2

Binary representations:

NumberBinary2nd bit
210ON
311ON
4100OFF
5101OFF
6110ON

Answer = 3


✅ 2. What Type of Problem Is This?

📌 Category:

  • Bit manipulation

  • Pattern observation

  • Prefix counting

  • Math-based periodicity


📌 Core DSA Concepts Being Tested

  • Binary representation

  • Understanding bit patterns

  • Efficient range counting

  • Turning range queries into prefix queries


📌 Mathematical Observation

Bits follow a repeating pattern.

For a fixed bit position X:

  • That bit repeats every:

    2X2^X
  • In every cycle of size 2X2^X:

    • First 2X12^{X-1} numbers → bit is OFF

    • Next 2X12^{X-1} numbers → bit is ON

So it behaves like:

Code
0000 1111 0000 1111 ...

(for X=3 example)

This periodicity is the key.


📌 Constraints Impact

  • Q can be 100,000

  • R can be up to 100,000

If we do O(R−L) per query, worst case:

105×105=101010^5 \times 10^5 = 10^{10}

❌ Impossible.

We need O(1) per query.


✅ 3. Naive / Brute Force Approach

For each query:

Code
count = 0
for i in range(L, R+1):
if (i >> (X-1)) & 1:
count += 1

Time complexity:

Worst case per query: O(R−L)

Worst case overall: O(Q × N) = 10¹⁰

❌ Too slow.


✅ 4. Optimization Insight

Instead of checking each number, we count directly using pattern math.


🎯 Core Trick

Define:

f(N,X)f(N, X)

= number of integers from 1 to N whose X-th bit is ON.

Then answer for range:

f(R,X)f(L1,X)f(R, X) - f(L-1, X)

This converts range query into prefix query.


🔎 How to Compute f(N, X)

Let:

block=2Xblock = 2^X

Each block:

  • First half → bit OFF

  • Second half → bit ON

Let:

Code
half = 2^(X-1)

Steps:

  1. Count full cycles:

    Code
    full_cycles = N // block

    Each full cycle contributes:

    Code
    half numbers
  2. Handle remaining part:

    Code
    remainder = N % block

    If remainder < half:
    → contributes 0

    Else:
    → contributes (remainder - half + 1)

So:

f(N)=full_cycles×half+max(0,remainderhalf+1)f(N) = full\_cycles \times half + max(0, remainder - half + 1)

💡 Why This Works

Because binary bits behave like a square wave:

Code
Length = 2^X
Pattern = [0...0, 1...1]

This repeats forever.

Instead of counting numbers,
we count complete patterns + leftover.


🔁 Pattern to Remember for Future

Whenever you see:

  • Count numbers in range

  • Bit at position X

  • Large Q

Think:

Bits follow periodic pattern of size 2^X

And convert:

range=prefix(R)prefix(L1)range = prefix(R) - prefix(L-1)

This pattern appears in:

  • Bit counting problems

  • Parity counting

  • XOR range problems

  • Power-of-two periodic behavior


✅ 5. Complexity of Optimal Approach

For each query:

  • Only arithmetic operations

  • No loops over range

Time Complexity:

O(Q)O(Q)

Space Complexity:

O(1)O(1)

This easily satisfies constraints.


✅ 6. Multiple Approaches?

Approach 1 (Best): Mathematical periodic counting

Time: O(1) per query
✔ Recommended


Approach 2: Precompute prefix arrays for each bit

You could build a 2D array:

Code
prefix[bit][i]

But:

  • 20 bits

  • N = 10^5

Memory is fine, but unnecessary.

Time complexity:

  • Precompute: O(20 × N)

  • Query: O(1)

Also valid.

But math approach is cleaner.


✅ 7. Clean Python Code (After Full Explanation)

Now here is the implementation:

Python
import sys
input = sys.stdin.read
data = input().split()

q = int(data[0])
index = 1

def count_upto(N, X):
if N <= 0:
return 0

block = 1 << X # 2^X
half = 1 << (X - 1) # 2^(X-1)

full_cycles = N // block
remainder = N % block

count = full_cycles * half

if remainder >= half:
count += remainder - half + 1

return count

results = []

for _ in range(q):
L = int(data[index])
R = int(data[index + 1])
X = int(data[index + 2])
index += 3

answer = count_upto(R, X) - count_upto(L - 1, X)
results.append(str(answer))

print("\n".join(results))

If you'd like, next we can:

  • Walk through a dry run manually

  • Derive the formula visually

  • Or convert this to C++ for practice

Your choice 👌

Friday, February 27, 2026

Kejriwal Acquitted -- But What About the Institutions?


See All News by Ravish Kumar
<<< Previous    Next >>>

In Indian politics, sometimes verdicts are not delivered only in courtrooms. They are delivered inside us — in our memory, in our trust, in the silences we maintain.

When a Special Court in Delhi said that no sufficient evidence was found against Arvind Kejriwal, Manish Sisodia, and 23 others in the alleged liquor policy case, it was not merely a legal conclusion. It was a moment that forced millions to pause. For months, prime-time debates had thundered with certainty. The word “scam” echoed nightly, repeated so often that doubt itself began to feel unreasonable. And yet, the court said: the charge sheets ran into thousands of pages, but contained gaps that testimony could not bridge. Not even a prima facie case was established.

This is not just about two politicians. It is about institutional credibility.

Investigative agencies in any democracy wield enormous power. But their greatest asset is not power — it is public trust. When a court observes that the prosecution failed to even make an initial case, it raises uncomfortable questions about the process itself. Arrests that stretched for months. Bail repeatedly opposed. Supplementary charges added. A sitting Chief Minister jailed while in office — something unprecedented in independent India. And in the end: insufficient evidence.

What does that do to faith in institutions?

For nearly two years, television studios functioned as parallel courtrooms. Accusations were presented as conclusions. Political spokespersons delivered nightly verdicts. Viewers were told, with conviction, that corruption had been exposed. The sheer repetition created its own truth. “If so much is being said, something must be there.” That psychological shift is perhaps more powerful than any legal document.

Now the court has spoken. And its words are stark.

This is where the deeper democratic tension emerges. In principle, investigative agencies are autonomous. In practice, timing shapes perception. When arrests coincide with election cycles, when bail orders are countered immediately with new cases, when opposition leaders across states face similar patterns of scrutiny — citizens are bound to ask whether law is being applied neutrally or strategically.

Democracy does not collapse in dramatic explosions. It erodes quietly — through normalization. Through the idea that arrest equals guilt. Through the belief that prolonged investigation itself is proof of wrongdoing. Through media trials that exhaust public patience before courts even begin proceedings.

There is also an uncomfortable mirror here for the judiciary. If, after prolonged incarceration and extensive filings, a case cannot sustain even a preliminary threshold, then the process itself becomes part of the story. Justice delayed may be justice denied — but justice pursued without adequate basis is also damaging. Not only to individuals, but to institutions.

The larger question is not whether Kejriwal or Sisodia feel vindicated. The larger question is what this episode tells us about the health of investigative autonomy in India. When agencies appear aligned with political narratives, their credibility suffers — even in cases where genuine wrongdoing might exist elsewhere. And once credibility is eroded, rebuilding it is far harder than filing another charge sheet.

There is also a caution for media. Debate is not journalism. Repetition is not evidence. Volume is not verification. When narratives harden before proof, the public sphere becomes polarized long before truth has a chance to breathe.

This verdict may restore some faith in judicial independence. But it simultaneously exposes the fragility of investigative trust. A democracy survives not because courts occasionally correct excesses — but because institutions act with restraint before excess becomes routine.

The most troubling aspect of this episode is not that leaders were accused. In a democracy, scrutiny is necessary. The troubling aspect is the possibility that accusation itself becomes political currency — that the process becomes punishment.

When that happens, even acquittal does not fully undo the damage. Reputations are scarred. Public discourse is distorted. Citizens grow cynical. And cynicism is fertile ground for authoritarian impulses.

The court has said there was no sufficient evidence. That is a legal fact. But the political and institutional consequences will linger far beyond the judgment.

In the end, democracies are not tested by how loudly allegations are made. They are tested by how carefully power is exercised — and how honestly institutions examine themselves when they fail.

Tags: Ravish Kumar,Hindi,Video,Indian Politics,

Quiz - Evaluating AI Agents (Short Course @ DeepLearning.ai)

View Course on DeepLearning.AI    View Other Courses Audited By Us


Thursday, February 26, 2026

Rebuilding Schools for the AI Age -- What If We Started From Scratch?


See All Articles on AI

Let’s be honest: something isn’t working.

U.S. high school seniors are at historic lows in reading, math, and science proficiency. College tuition has exploded nearly 9x since the 1980s. And yet college graduates are now among the longest unemployed groups. At the same time, AI is reshaping entire industries in real time.

If this is the trajectory, we have to ask a hard question:

If we were going to redesign school from first principles for the AI age… what would we build?

That’s the question behind Alpha School, an education model that claims something almost heretical:

Kids can learn 2–10x faster.
Academics can be done in two hours a day.
And school should be something children love more than vacation.

Radical? Absolutely.
Necessary? Increasingly, yes.


The Core Problem: School Is Stuck in 1900

For 40 years, learning scientists have known something uncomfortable:
The “teacher in front of a classroom” model is not the most effective way to teach.

Research going back to Benjamin Bloom’s “Two Sigma Problem” showed that one-on-one mastery-based tutoring dramatically outperforms traditional classrooms. The issue wasn’t knowing what works. The issue was scale.

Until now.

AI has changed the equation.

Instead of one teacher delivering the same lesson to 30 students at the same pace, generative AI can create personalized lessons for every child—at exactly the right level of difficulty.

Not too easy (which breeds boredom).
Not too hard (which breeds disengagement).
Right in the “zone of proximal development.”

The result? Kids move faster because they’re no longer trapped in time-based progression. They advance when they master, not when the calendar flips.

That shift—from time-based to mastery-based—changes everything.


The First Radical Principle: Kids Must Love School

Here’s the most counterintuitive insight:

Alpha’s founders argue that love of school isn’t a luxury metric—it’s the foundation.

In most traditional systems, we accept that school is “supposed to be hard” or even unpleasant. Spinach. Necessary but joyless.

But in every other domain—companies, sports teams, creative studios—we obsess over building environments people want to show up to.

Why should school be different?

At Alpha, over 90% of students report loving school. Some reportedly choose school over vacation. That sounds absurd—until you see the structure.


The Two-Hour Academic Engine

Students complete core academics in just two focused hours per day.

Not Zoom lectures.
Not passive screen time.
Not ChatGPT cheating.

Instead:

  • Personalized AI-generated lessons

  • Continuous feedback loops

  • Screen monitoring that detects guessing, distraction, or rushing

  • Real-time coaching toward productive learning behaviors

The platform measures “XP” (focused minutes of learning).
Waste time? The system flags it.
Engage deeply? You move forward faster.

This isn’t more screen addiction—it’s high-efficiency learning.

And when academics compress into two hours?

You get time back.


The Afternoon: Where Life Actually Happens

This is where the model gets interesting.

If kids aren’t chained to desks all day, what do they do?

They build.

They launch businesses.
They produce musicals.
They create apps.
They design marketing campaigns.
They climb rock walls.
They study financial literacy.
They practice public speaking.

Instead of treating “life skills” as electives, they become core curriculum.

Leadership.
Entrepreneurship.
Teamwork.
Adaptability.
Grit.

In an AI-saturated future, those may matter more than memorizing formulas.


A Different Role for Adults

Traditional schools ask teachers to do five jobs:

  • Be subject expert

  • Design curriculum

  • Deliver lectures

  • Grade work

  • Motivate students

That’s an impossible spec.

Alpha removes curriculum design and grading from humans and gives those to software. What remains?

Mentorship.

Their adults—called “guides”—focus on:

  • High standards

  • Emotional support

  • Weekly one-on-one coaching

  • Motivational accountability

The average student-teacher one-on-one time in traditional schools? About 22 seconds per day.

At Alpha? 30 minutes per week, guaranteed.

That changes relational depth.


The Dilemma: Screens, Skepticism, and Scaling

This model raises real concerns.

What about screen time?
Parents are pushing back against devices. Alpha’s response is: there’s good screen time (focused learning that frees the rest of the day) and bad screen time (passive consumption). The difference is intentionality and structure.

What about cheating with AI?
They block chatbots during core academics. AI is used to generate lessons, not to do the work for students.

What about scale?
This is harder.

Private micro-schools can innovate quickly. Public systems move slowly. Charter applications get rejected. Regulatory inertia is real.

And then there’s cost. Advanced AI tutoring at scale isn’t cheap yet. Token usage alone runs high. But like all technology, costs fall.

The real bottleneck may not be tech.

It may be parents.

As one founder put it:
“The biggest impediment to education reform isn’t students. It’s what parents believe school is supposed to look like.”

That’s a cultural challenge, not a technical one.


Why This Matters Now

AI isn’t coming. It’s here.

Kids entering kindergarten today will graduate into a world where:

  • Entire job categories disappear.

  • New ones emerge overnight.

  • Knowledge is ubiquitous.

  • Adaptability becomes survival.

In that world, memorization declines in value.
Learning how to learn becomes everything.

What Alpha is attempting isn’t just a school redesign. It’s a philosophical shift:

From passive consumption → active creation.
From time-based sorting → mastery-based growth.
From compliance → agency.
From pessimism → optimism.


The Bigger Question

Is Alpha the final answer?

Probably not.

But it may be an early prototype of what’s coming.

The more important takeaway isn’t whether every detail works perfectly. It’s that someone is asking the right question:

If we were building education for the AI age from scratch… would we build what we have now?

If the honest answer is no, then experimentation isn’t optional.

It’s urgent.

And perhaps the boldest idea of all is this:

In a future where AI gives children superpowers,
the real job of school isn’t to slow them down.

It’s to help them aim higher.

Tags: Artificial Intelligence,EdTech,