Friday, May 8, 2026

Six Months To Live (May 2026)


My Meditations    « Previously    Next »

“If you learned today that you only had six months left to live, how would you spend your last six months on earth?”

(Read more about this question »)

I thought about this topic for about 30-40 minutes and I realized in such 6 months I would be busy repairing my relationships and I would be busy managing my finances (or debts to be specific and clear).

I could be more sensitive, respectful and careful in my relationships but I can't really try to mechanically try to fix them like a broken toy or gadget.

For my finances, I would really need to be watchful of where money goes and how I spend it.

My debts aren't exactly problematic because I have got them covered but I think about them for two reasons:
    1. Debts are still Debts. 
    2. The money which I am spending towards EMIs could have been used towards creating a financial cushion, a safety net.

In this way, debts aren't the exact problem but poor money management is.
Also, what concerns me is if people (in my relationships) would be able to do well financially after I am gone (that thought is despite how broken my relationships are).

~~~

Having written this much already makes me feel a bit lighter 😀

I am thinking after I would have made some progress towards my relationships and finances, I would devote some time (or rest of my time) towards my spiritual wellbeing.

I would practice forgiveness. And humility. And also the other of ten Jain virtues…

Wish you well!
Thank you for reading!

My Meditations    « Previously    Next »

Ask ‘Why’ Five Times…


My Meditations    « Previously    Next »

Asking ‘Why’ five times to clarify my intentions and motivations, deeper reasons, personal values and motivations of why I do that what I do...

    1. Why do you study ML (or algorithms, or whatever)?

To be able to crack interviews.

    2. Why do you want to crack interviews?

To be able to get a project (before today: it was to get a better job)

    3. Why do you want to get a project / job?

To earn money.

    4. Why do you want to earn money?

To live a comfortable life… with, maybe, decent standards of living.

Well, no, I responded to question in two points in the above answer almost to the point of justifying my current situation and way of life.

So, I would rather say: “To live comfortably” 

But then even now it seems to reveal an escalating loop in my thinking: “I am choosing an uncomfortable way of life to seek a comfortable life.”

And the grey area appears: I don't want to think of my way as the way of delayed gratification. Because no book on delayed gratification tells you how delayed it is going to be.

And then I recall my learnings from Buddhism and reckon “There is no such thing as comfortable life. Everyone suffers.”

    5. THE LAST ‘WHY’

Assuming my last answer (“to live comfortably“) was okay and accepted.

Then I ask again “Why live comfortably?”

I am not getting any thoughts, other than thinking of myself as a hedonist... 

My Meditations    « Previously    Next »

Mind Your Own Matters


My Meditations    « Previously    Next »

I have been in a lot of mess, a lot of chaos, a lot of trouble because of one mistake, one habit – I don't mind my own business.

As I try to see its truthfulness, its validity, I see it in play in most (if not all) of my relationships and equations with other people.

Somebody comes to me with a problem and I tend to make it a personal task, goal to accomplish.

My maid asks for help in police verification for working in the society and I make it a personal mission – she may neither be that appreciative of my help, nor may be critically needing it.

Some girl in my society in first year of college asks for my help with Math and Python, and I make that a personal mission. Even when (same as before) she might neither be that appreciative of my help, nor may be critically needing it.

My mom calls me and tells me of some issue with some tenant, or some issue with water, or electric, or some tool or equipment, and I would be totally distracted from what I would be doing. Packing my things and leaving for Tri Nagar. And then when things are sorted, my mom would be telling me that “my personal intervention was not needed”. I then at such times think (for no reason) to myself “why did she call me then to rant?”

At the NGO I went to for the last two months to teach, I thought of it as a personal responsibility, and felt an onus for it to make sure that the kids there learn something. Even when their parents and the kids themselves don't see much value in it, though the kids cannot be blamed given their age. And this is not my assumption, I see it in absenteeism and falling attendance.

The same thing applies to my blogging activity – what do I have to do with Iran? What do I have to do with Bihar? What do I have to do with Bengal? What do I have to do with Delhi? Nothing, nothing and nothing – but I still write, I still blog, still waste my time and energy.

Then came the moment of realisation…

Yesterday afternoon, I was at Bikaner Sweets to buy some sweets and namkeen. There I saw an electric kitchen appliance that was frying samosas in an oil pool. I was totally excited to see that and could not hide my excitement. I asked “is that an electric appliance for making samosas?... Is that an electric appliance for making samosas?” Then the old bitter-and-sour man sarcastically remarked, “No, that's running on gobar-gas!” (Gobar: cow dung) I went quiet. I thought about it. And put in my pocket the lesson he meant to impart… ~~~ Thanks for reading!

My Meditations    « Previously    Next »

Thursday, May 7, 2026

Is this my awesome stuff? (A Lesson in Financial Literacy)


See All TED Talks on Financial Literacy    « Previously


Personal Finance  ·  Mindful Living

What if More Was Never Going to Make You Happy?

"He had everything we're taught to chase — the money, the stuff, the freedom. And still, it was never enough."

On the story that changed everything

My father was the kind of man who could light up a room without trying. He had a Harley, a big house, a revolving door of exciting friends, and an appetite for adventure that never dimmed. He once told me he wanted to travel to the Congo just to see a gorilla in the wild. That was him — always chasing the next extraordinary thing.

But I knew a different version of that man. I knew the father who missed every single hockey game I ever played. I remember scanning the stands during one particular game, the one he'd promised to attend. He wasn't there. He'd gone out with friends instead. Over the years, my mother left him, his brother stopped calling, and my own brother cut him off entirely — he didn't even know he'd gotten married. My father never met my boys. He died alone on a boat at fifty-four.

He spent his whole life chasing more. And it was never, ever enough.


The Lie We've All Been Told

Here's the belief that ruined my father's life — and one that I carried into my own for far too long: if only I had a little more, I'd finally be happy.

I remember the day I walked through the front door of my dream home. I felt it — that warm rush of I've made it. Then one afternoon, standing in my beautiful backyard with its sunken garden and gazebo, I noticed something: I couldn't hear my boys anymore. They were too far away. The house I'd worked so hard for had quietly created distance between me and the people who mattered most.

That moment stopped me cold. What if I had believed a lie? What if more would never make me happy?

That question sent me down a long road of studying money — not to accumulate it, but to understand it. Why do we want it? What are we really chasing? And what does it cost us when we chase it blindly? Those questions are also why I now teach children about money — not just how to earn and save it, but how to think about it.


The Awesome Stuff Experience

A few years ago, I took my boys, Will and Noah, to Disneyland. Before we walked through the gates, I gave them each twenty dollars and said: "This is your money. Do whatever you want with it. But before you spend a single cent, I want you to try three things."

What followed became one of the most powerful financial lessons I've ever witnessed — and it started not with a spreadsheet or a savings account, but with a pause and a simple question.

Here's what I asked them to do. Close your eyes. Hold out your left hand and think about something you really want to buy right now — a gadget, a pair of shoes, that shiny thing in the window. Got it? That's your "awesome stuff" in this moment.

Now keep your eyes closed. Hold out your right hand. This time, think of something different — maybe it's not a thing at all. Maybe it's laughing so hard your stomach hurts and you still can't stop. Maybe it's being truly present for someone you love when they need you most. Maybe it's watching the sunrise with a person who means everything to you. Hold that in your right hand.

Open your eyes. Look at both hands. Which would you choose?

Sometimes it's still the thing in your left hand — and that's completely fine. But sometimes, the shift is instant. The thing you wanted a moment ago just doesn't seem to matter as much. That feeling — that quiet internal recalibration — is the magic. And it all starts with a pause.

The goal isn't to choose less. It's to choose what matters more — and to know the difference before you spend.

Three Steps That Change Everything

The Awesome Stuff Experience isn't a one-time experiment. It's a system — a daily practice for how we spend, save, and give. It comes down to three things.

1

Pause and Ask: Is This My Awesome Stuff?

Before any purchase, big or small, take one breath and ask yourself honestly: Is this the thing I actually want, or am I just reacting to the moment? Awareness is the difference between impulse and intention. Will saw a toy plane at Disneyland, picked it up, put it back in his mind — then bought it anyway. And that's okay. The point isn't to say no. The point is to stop buying on autopilot. He chose it; he didn't just grab it. That distinction matters more than the price tag.

2

Save for Freedom, Not for Things

We've been taught to save with a destination in mind — a bigger purchase, a vacation, an upgrade. But that's really just delayed spending. True saving is different. It's letting your money grow and work for you so that one day you have the freedom to say yes to what really matters. I asked Will and Noah to save just 20% of the twenty dollars I gave them — not as a rule, but as a question: Is there a freedom you'd like to protect? Even 5% or 10% compounded over time creates options. And you can start today, even if you didn't start yesterday.

3

Give Because You Can

We often teach generosity as an obligation — give because you have more than others, because you should be grateful, because someone is less fortunate. But that framing creates a hierarchy; it turns giving into a transaction. What if we gave simply because we could? Because it feels good, because it connects us, because the things that matter most are almost never the things we keep — they're the ones we share. That day in Disneyland, everyone received a free collector's pin for Mickey and Minnie's birthday. Later in the queue, Will overheard an older woman telling a cast member she hadn't received one. Without hesitation, he walked over and gave her his. The look on her face was unforgettable — as though, for just a moment, she had been truly seen. I caught a glimpse of the man my son is becoming.


A New Money Story

My father passed down one money story — chase more, and happiness will follow. I want to pass down a different one.

The next time a child asks you to buy them something, or you catch yourself reaching for your wallet out of habit, try something first. Pause. Ask the question. Is this my awesome stuff?

It sounds almost too simple. That's the point. After spending most of my life studying money and what it does to people — the lives it builds and the lives it quietly hollows out — I've come to believe there are really only three things worth knowing:

What Actually Matters

  • What matters most is rarely a thing. It's people, connection, and meaning.
  • The simplest path to financial freedom is to always save first — before you spend, not after.
  • You don't need to wait until you have more to give. You can give today, and it doesn't have to cost anything at all.

Financial literacy doesn't have to be a dry subject of compound interest and debt ratios. It can be a conversation about what you actually value. It can be a question you ask at a checkout counter, a moment of pause before a purchase, a small act of generosity on an ordinary Tuesday.

Imagine a world where every child learns to seek meaning over more. Where the pause becomes second nature. Where saving isn't deprivation and giving isn't sacrifice — they're just how you live.

We can build that world. It starts with a single question.


See All TED Talks on Financial Literacy    « Previously
Tags: Investment,Video,

Costliest Data Plan (Medium Complexity Problem on Bit Manipulation)

Index of "Algorithms: Design and Analysis"    « Previous

Basic Programming > Bit Manipulation > Basics of Bit Manipulation

Problem

Explanation

In the first case, the data plans cost 10rs and 5rs, With the first data plan(10rs) we can invite 1st and the 3rd friend because in the binary representation of 10  (1010) the first and the third bit are set, and with the second data plan (5rs), we can invite 0th and the 2nd friend because in the binary representation of 5(101), the 0th and the 2nd bit is set

Now with all the data plans, we could invite the 0th, 1st, 2nd, and 3rd friends, but if we remove any data plans, there will be a friend who will be left. Therefore the answer is 0rs

In the second case, the cost of all the data plans is the same, so if we remove any one data plan, we will still be able to invite all the friends we invited before. Therefore the answer is 9rs
Solve on HackerEarth

Note about the problem

Difficulty: Easy
Attempted by: 1441
Success Rate: 88%
Points Assigned: 20

Actual Complexity For Me: Medium/Hard

Prompt to DeepSeek/ChatGPT

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 (*In Layman Terms In Explanatory Tone*) 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.

# OUTPUT SPECIFICATION

- Format your response as a HTML and return HTML file only.
- Wrap the HTML contents in a 
with class="customOuterWrapper" - Write CSS rules starting with "div.customOuterWrapper ..." only - Do not write any generic / global CSS rules.

Response from DeepSeek-V3 (Deep Think as Expert)

Problem Restatement

Pawan has friends labeled by unique non‑negative integers 0, 1, 2, … He buys N data plans. Each plan i has a cost aáµ¢ (a non‑negative integer). When Pawan uses a plan with cost Y, a friend f receives an invitation if and only if the f‑th bit (0‑indexed) in the binary representation of Y is 1. A friend attends the party if they receive at least one invitation from any plan.

The set of all invited friends is exactly the bitwise OR of all plan costs. Pawan wants to remove at most one data plan and still invite exactly the same set of friends as before. The money saved is the cost of the removed plan. We must find the maximum possible cost he can save. If no plan can be removed without losing some friend, the answer is 0.


1. Problem Category & Core Concepts

  • Category: Bit manipulation / Greedy.
  • Core DSA: Bitwise operations (OR, AND, bit counting), frequency maps, set‑wise reasoning.
  • Mathematical Observation: The set of invited friends is the union of the bits set in any plan. Removing a plan is safe iff every bit that plan provides is also provided by at least one other plan.
  • Constraints:
    • Test cases t ≤ 100, sum of N ≤ 10⁶.
    • Each aáµ¢ ≤ 10⁹ → fits in 30 bits (0…29).
    • Time limit implies we need O(bit‑length ⋅ total N) or better.

2. Naïve / Brute‑Force Approach

For each data plan, remove it, compute the bitwise OR of the remaining plans, and compare with the original total OR. If they match, the plan is “removable”. Take the maximum cost among all removable plans.

Complexity: O(N²) per test case (computing OR for each removal), which is far too slow when N is large (total N ≤ 10⁶ would become ~10¹² operations).

3. Key Insight & Optimisation

Instead of recomputing the whole OR every time, notice that a plan is only essential if it is the sole provider of at least one bit that is set in the total OR. In other words:

A plan can be removed if and only if it has NO bit for which it is the only plan with that bit set.

Why does this work?

  • Every friend (bit) that was invited originally must still receive an invitation.
  • If a bit is set in at least two plans, we can drop any one of them and the bit remains present.
  • If a bit is set in exactly one plan, dropping that plan makes that bit disappear → the set of invited friends shrinks.

Pattern to remember: “Union preservation under removal of one element” is equivalent to checking which elements own a “unique” property (a bit that appears exactly once). This pattern appears often in problems involving OR/AND/XOR and frequency counts over bits.

4. Step‑by‑Step Optimal Algorithm

  1. Count, for every bit position 0…30, how many plans have that bit set. Also record the overall OR.
  2. Build a “unique mask” containing all bits whose frequency is exactly 1.
  3. Any plan that shares no bit with this unique mask is removable (its bits are all covered by other plans).
  4. Answer = maximum cost among all removable plans; 0 if none exist.

Complexity:

  • Time: O( (number of set bits in all numbers) + N + 31 ) ≈ O(31·N) worst‑case. With total N ≤ 10⁶ this is ~3×10⁷ operations, well within limits.
  • Space: O(31) for the frequency array → O(1) extra space.

5. Python Implementation

import sys

def solve() -> None:
    data = sys.stdin.buffer.read().split()
    it = iter(data)
    t = int(next(it))
    out_lines = []
    
    for _ in range(t):
        n = int(next(it))
        a = [int(next(it)) for _ in range(n)]
        
        # 10^9 < 2^30, so bits 0..29 are enough; using 31 for safety
        freq = [0] * 31
        
        for x in a:
            v = x
            # iterate over set bits only
            while v:
                lsb = v & -v
                b = lsb.bit_length() - 1
                freq[b] += 1
                v ^= lsb   # clear the lowest set bit
        
        # Build mask of bits that occur in exactly one plan
        unique_mask = 0
        for b in range(31):
            if freq[b] == 1:
                unique_mask |= (1 << b)
        
        best_saving = 0
        for x in a:
            # If x has no unique bit, it can be dropped
            if (x & unique_mask) == 0:
                if x > best_saving:
                    best_saving = x
        
        out_lines.append(str(best_saving))
    
    sys.stdout.write("\n".join(out_lines))

if __name__ == "__main__":
    solve()

6. Example Walkthrough

  • Case 1: plans = [10, 5] → bits: 10=1010₂, 5=0101₂. OR = 1111₂. Every bit appears exactly once → unique_mask = 1111₂. Both plans touch it → none removable → answer 0.
  • Case 2: plans = [9, 9, 9, 9] (or four equal costs). Bits of 9=1001₂ appear 4 times each → unique_mask = 0. All plans are removable → answer 9 (the cost).

Key Takeaway: When dealing with “can I remove one element without changing a bitwise OR / union”, count how many elements supply each bit and identify the elements that are the sole supplier of at least one bit. The rest are safe to remove.





def solve():
    t = int(input())

    for _ in range(t):

        n = int(input())

        a = list(map(int, input().split()))

        # frequency of each bit
        freq = [0] * 31

        for x in a:
            v = x

            # iterate over set bits only
            while v:
                lsb = v & -v
                b = lsb.bit_length() - 1

                freq[b] += 1

                v ^= lsb

        # mask containing bits that appear exactly once
        unique_mask = 0

        for b in range(31):
            if freq[b] == 1:
                unique_mask |= (1 << b)

        best_saving = 0

        for x in a:

            # removable if it contributes no unique bit
            if (x & unique_mask) == 0:

                if x > best_saving:
                    best_saving = x

        print(best_saving)


if __name__ == "__main__":
    solve()

Time (sec): 0.82564
Memory (KiB): 11824




A Slightly Simpler Implementation (Just one Modification)


def solve():
    t = int(input())

    for _ in range(t):

        n = int(input())

        a = list(map(int, input().split()))

        # frequency of each bit
        freq = [0] * 31

        for x in a:
            for b in range(31):
                if x & (1 << b):
                    freq[b] += 1
            

        # mask containing bits that appear exactly once
        unique_mask = 0

        for b in range(31):
            if freq[b] == 1:
                unique_mask |= (1 << b)

        best_saving = 0

        for x in a:

            # removable if it contributes no unique bit
            if (x & unique_mask) == 0:

                if x > best_saving:
                    best_saving = x

        print(best_saving)


if __name__ == "__main__":
    solve()

Time (sec): 1.09442
Memory (KiB): 14348




Conversation Log With ChatGPT 5.3

Here’s the problem in plain words:

You have N data plans. Each plan number is also a bitmask of friends it can notify: if bit i is set in a plan’s value, then friend i gets notified by that plan.

Pawan wants to remove at most one plan and still notify exactly the same set of friends as before. Since the cost of a plan is equal to its value, the amount of money saved is the value of the removed plan. Your job is to find the maximum cost plan that can be removed without changing the set of notified friends. If no plan can be removed, answer is 0.

1) What kind of problem is this?

This is mainly:

  • Bit manipulation

  • Greedy / checking redundancy

  • A little like set coverage using bits

2) Core DSA concepts being tested

  • Bitwise OR

  • Counting how many numbers contain each bit

  • Checking whether an element is “essential” or “redundant”

3) Important mathematical observation

The total set of notified friends is just the bitwise OR of all plans.

A plan can be removed iff every bit set in that plan is also present in at least one other plan.

Why?
Because if a bit appears only in that one plan, removing it would make that friend lose notification.

So the condition for a plan a[i] to be removable is:

  • for every bit set in a[i], the count of that bit across the whole array is at least 2

4) Brute force idea

For every plan:

  1. Remove it temporarily

  2. Compute OR of all remaining plans

  3. Compare with original OR

Why brute force is too slow

If you do this by scanning the whole array for every index, that becomes O(N^2) in the worst case.

With N up to 10^5, that is too slow.

5) Key optimization / trick

Instead of recomputing OR again and again, count how many times each bit appears in the whole array.

Then for each number:

  • look at its set bits

  • if all those bits have frequency > 1, the number is removable

This works because OR is just a union of bits.
A bit disappears only if the removed number was the only one containing it.

Pattern to remember

Whenever a problem says:

  • “remove one element”

  • “still preserve the same OR / union / coverage”

think:

“Check whether every feature of that element is covered by others.”

6) Multiple valid approaches

Approach 1: Bit counts

  • Best and simplest here

  • Time: O(N * 31)

  • Space: O(31)

Approach 2: Prefix OR / suffix OR

  • Compute OR before each index and after each index

  • Then OR of all except i can be found quickly

  • Time: O(N)

  • Space: O(N)

For this problem, bit counts are cleaner because values are up to 1e9, so only about 31 bits matter.

7) Complexity

Let B = 31 because a[i] <= 10^9.

  • Time: O(N * B)

  • Space: O(B)

This easily fits the constraints because 31 * 10^5 is small enough.

8) Python code

Python
import sys

def solve():
data = list(map(int, sys.stdin.buffer.read().split()))
t = data[0]
idx = 1
out = []

for _ in range(t):
n = data[idx]
idx += 1
arr = data[idx:idx + n]
idx += n

# Count how many numbers contain each bit
bit_count = [0] * 31 # enough for ai <= 1e9

for x in arr:
b = 0
while x:
if x & 1:
bit_count[b] += 1
x >>= 1
b += 1

ans = 0

for x in arr:
removable = True
temp = x
b = 0
while temp:
if temp & 1:
if bit_count[b] == 1:
removable = False
break
temp >>= 1
b += 1

if removable:
if x > ans:
ans = x

out.append(str(ans))

sys.stdout.write("\n".join(out))

if __name__ == "__main__":
solve()

If you want, I can also show a prefix/suffix OR version and explain why it works on the same sample.




Let’s understand the prefix/suffix OR approach carefully.


Core Idea

Suppose you want to know:

“What is the OR of all elements except index i?”

Instead of recomputing it every time, precompute:

  • prefix[i] = OR of elements from 0 to i

  • suffix[i] = OR of elements from i to n-1

Then:

OR of all except i
=
prefix[i-1] OR suffix[i+1]

This is a very common technique in DSA:

“Precompute information from left and right so removing one element becomes O(1).”


Step-by-Step Example

Suppose:

arr = [10, 5]

Binary:

10 = 1010
5 = 0101

Total OR:

1010
0101
----
1111 = 15

So originally all friends represented by bits 0,1,2,3 are notified.


Build Prefix OR

prefix[0] = 10

prefix[1] = prefix[0] | arr[1]
= 10 | 5
= 15

So:

prefix = [10, 15]

Build Suffix OR

suffix[1] = 5

suffix[0] = arr[0] | suffix[1]
= 10 | 5
= 15

So:

suffix = [15, 5]

Remove Each Element

Remove index 0

OR of remaining:

suffix[1] = 5

Compare with total OR:

5 != 15

So cannot remove 10.


Remove index 1

OR of remaining:

prefix[0] = 10

Compare:

10 != 15

Cannot remove 5.

Answer = 0.


Another Example

arr = [9, 9, 9, 9]

Binary:

1001
1001
1001
1001

Total OR = 9.

If we remove any one element:

Remaining OR still = 9.

So maximum removable = 9.


Why This Works

Bitwise OR has this important property:

(A OR B OR C OR D)
without C
=
(prefix before C) OR (suffix after C)

Because OR is:

  • associative

  • commutative

Same pattern appears in:

  • product except self

  • sum except self

  • XOR except self

  • max/min outside range


Complexity

Building prefix

O(N)

Building suffix

O(N)

Checking all removals

O(N)

Total:

Time:  O(N)
Space: O(N)

Comparison With Bit Count Approach

ApproachTimeSpaceIdea
Bit-countO(N * 31)O(31)Track bit frequencies
Prefix/Suffix ORO(N)O(N)Compute OR except self

Which One Is Better Here?

Bit-count approach

Pros:

  • Less memory

  • More “bit-manipulation oriented”

  • Elegant

Cons:

  • Slightly trickier to think about initially


Prefix/Suffix approach

Pros:

  • Easier to generalize

  • Cleaner conceptually

  • Very reusable pattern

Cons:

  • Uses extra arrays


Prefix/Suffix OR Code

Python
import sys

def solve():
data = list(map(int, sys.stdin.buffer.read().split()))
t = data[0]
idx = 1

answers = []

for _ in range(t):
n = data[idx]
idx += 1

arr = data[idx:idx + n]
idx += n

# Build prefix OR
prefix = [0] * n
prefix[0] = arr[0]

for i in range(1, n):
prefix[i] = prefix[i - 1] | arr[i]

# Build suffix OR
suffix = [0] * n
suffix[-1] = arr[-1]

for i in range(n - 2, -1, -1):
suffix[i] = suffix[i + 1] | arr[i]

total_or = prefix[-1]

ans = 0

for i in range(n):

if n == 1:
remaining_or = 0

elif i == 0:
remaining_or = suffix[1]

elif i == n - 1:
remaining_or = prefix[n - 2]

else:
remaining_or = prefix[i - 1] | suffix[i + 1]

if remaining_or == total_or:
ans = max(ans, arr[i])

answers.append(str(ans))

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

if __name__ == "__main__":
solve()

A very important takeaway pattern from this problem:

If a question asks:
“What happens if I remove one element?”

Think about:

  • prefix/suffix preprocessing

  • frequency counting

  • contribution of each element

That pattern appears constantly in DSA interviews and contests.




what is this code doing:

 for x in a:
            v = x

            # iterate over set bits only
            while v:
                lsb = v & -v
                b = lsb.bit_length() - 1

                freq[b] += 1

                v ^= lsb


Explain in layman terms

This code is doing one specific job:

“For every number, find which bits are ON (1), and count them.”

But it does it in a very clever and efficient way.

Let’s break it down slowly in plain English.


First: What is a “set bit”?

A set bit means a bit that is 1.

Example:

10 = 1010

Bits ON are:

  • bit 1

  • bit 3

(Counting from right starting at 0)


Goal of this code

Suppose:

Python
a = [10, 5]

Binary:

10 = 1010
5 = 0101

We want to count:

bit 0 appears how many times?
bit 1 appears how many times?
bit 2 appears how many times?
...

The Code

Python
for x in a:
v = x

while v:
lsb = v & -v
b = lsb.bit_length() - 1

freq[b] += 1

v ^= lsb

Now let’s understand each line.


Step 1

Python
for x in a:

Take each number one by one.

Example:

x = 10

Step 2

Python
v = x

Make a copy because we will modify it.

So:

v = 10

Binary:

1010

Step 3

Python
while v:

Keep going while the number is not zero.


The Important Trick

Python
lsb = v & -v

This extracts the rightmost ON bit.


Example

Suppose:

v = 1010

Then:

lsb = 0010

Why?

Because this trick isolates the lowest set bit.


Visual Intuition

1010

The rightmost 1 is here:

   ^

So:

0010

gets extracted.


Next Line

Python
b = lsb.bit_length() - 1

This finds:

“Which bit position is this?”

Example:

0010

means bit position 1.

So:

Python
b = 1

Next

Python
freq[b] += 1

Increase count for that bit.

Meaning:

bit 1 appeared once more

Final Trick

Python
v ^= lsb

This removes that bit from the number.

Example:

1010
^0010
-----
1000

Now:

v = 1000

The lowest set bit was removed.


Loop Continues

Again:

1000

Rightmost ON bit is:

1000

Position = 3

Increase:

freq[3] += 1

Remove it:

1000 ^ 1000 = 0000

Now loop stops.


So What Happened Overall?

For number 10:

1010

We found:

  • bit 1 is ON

  • bit 3 is ON

WITHOUT checking all 31 bits.


Why Is This Clever?

A beginner solution would do:

Python
for b in range(31):
if x & (1 << b):
freq[b] += 1

This checks EVERY bit.

Even if only 2 bits are ON.


This Optimized Version

Checks ONLY the ON bits.

If a number has:

  • 2 set bits → only 2 iterations

  • 5 set bits → only 5 iterations

Much faster.


Main Pattern to Remember

These are classic bit tricks:

1. Extract lowest set bit

Python
x & -x

Meaning:

“Give me the rightmost 1-bit.”


2. Remove lowest set bit

Python
x ^= (x & -x)

or equivalently:

Python
x &= (x - 1)

Meaning:

“Delete the rightmost 1-bit.”


Layman Analogy

Imagine a number as a row of glowing bulbs:

1010

The code repeatedly:

  1. Finds the first glowing bulb from the right

  2. Notes its position

  3. Turns it off

  4. Repeats until all bulbs are off

That’s exactly what this loop is doing.


Index of "Algorithms: Design and Analysis"    « Previous