Monday, May 19, 2025

Discussion on "Remove Consecutive Duplicates" Problem

To See All Articles About Technology: Index of Lessons in Technology
Problem: Remove Consecutive Duplicates

Given a string s, remove all consecutive duplicate characters and return the resulting string.

Input Format

A single line containing a string s (1 ≤ length of s ≤ 1000)

The string will contain only lowercase English letters.

Output Format

Print the string after removing consecutive duplicate characters.

Sample Input 1

aabbccddeee

Sample Output 1

abcde

Sample Input 2

aabaaabb

Sample Output 2

abab

~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~

Can you ask me a (that may be simple at rating of about 3/10) coding problem that tests problem solving skills of the candidate?

Sure! Here's a simple (3/10 difficulty) coding problem that tests basic problem-solving, string handling, and logic skills:


Problem: Remove Consecutive Duplicates

Given a string s, remove all consecutive duplicate characters and return the resulting string.


๐Ÿ”น Input Format

  • A single line containing a string s (1 ≤ length of s ≤ 1000)

  • The string will contain only lowercase English letters.


๐Ÿ”น Output Format

  • Print the string after removing consecutive duplicate characters.


๐Ÿ”น Sample Input 1

nginx
aabbccddeee

๐Ÿ”น Sample Output 1

nginx
abcde

๐Ÿ”น Sample Input 2

nginx
aabaaabb

๐Ÿ”น Sample Output 2

nginx
abab

๐Ÿง  What it tests

  • Understanding of string traversal

  • Use of conditionals

  • Handling edge cases like repeated or single characters


Let me know when you're ready for the solution or hints!

Can you critique this rough algo:

s = "afafasgggewrtdg"
t = ""
last_seen_character = ''
streak_found = False
for c in s: 
    if c not in t: 
        t += c
        last_seen_character = c
    elif c in t and last_seen_character == c: 
        streak_found = True
        last_seen_character = c
        continue
    else (c in t) and last_seen_character != c and not streak_found:
        t += c
        last_seen_character = c
        streak_found = False

Thanks for sharing your rough algorithm! You're clearly thinking through the logic and edge cases, which is great. Let’s break down the approach and evaluate it step by step.


๐Ÿ” Your Goal:

You want to remove consecutive duplicate characters from a string.


What’s good in your approach:

  1. Tracking state: You're maintaining last_seen_character — that’s useful for detecting consecutive repeats.

  2. Use of flags: You introduced streak_found to handle streaks, though it's a bit more complex than needed for this problem.

  3. Good intent: You’re trying to avoid adding characters that have already been added if they’re part of a consecutive streak.


Issues in the Logic:

  1. Wrong check for character presence in t:

    • You’re checking if c not in t, but this checks if the character has ever occurred in t, not if it's the same as the previous one.

    • This can cause issues with strings like "aabaaabb" — you'll incorrectly skip valid characters.

  2. Incorrect else condition:

    • Python syntax error: else (c in t) and ... is invalid.

    • else doesn’t take a condition. You’d need to use elif again.

  3. Unnecessary use of streak_found:

    • You don’t need a streak_found flag. You only need to compare each character to the one immediately before it.

  4. Adding characters that are not duplicates but previously seen:

    • You're preventing characters from being added again even if they're not consecutive — which is incorrect.


Correct Logic Should Be:

Keep the character only if it’s not equal to the previous character.


✔️ Cleaned Up Version of the Algorithm:

python
s = "afafasgggewrtdg" t = "" last_seen_character = None for c in s: if c != last_seen_character: t += c last_seen_character = c print(t)

๐Ÿงช Example:

Input: "aabaaabb"
Output: "abab"


⏱️ Time Complexity: O(n)

You visit each character once.

๐Ÿ“ฆ Space Complexity: O(n)

In the worst case, the output string could be the same length as input.


๐Ÿง  Final Thoughts:

You're on the right track with tracking characters, but overcomplicating it with multiple conditions and flags. Stick to comparing only the current and previous characters — that’s sufficient here.

Let me know if you want to walk through more test cases or edge conditions!


So The Solution Is:

s = "afafasgggewrtdg"
t = ""
last_seen_character = None

for c in s:
    if c != last_seen_character:
        t += c
    last_seen_character = c

print(t)

Sunday, May 18, 2025

AI Revolution Is Underhyped (Eric Schmidt at TED)

To See All Articles About Technology: Index of Lessons in Technology

AI’s Quantum Leap: Eric Schmidt on the Future of Intelligence, Global Tensions, and Humanity’s Role

The AlphaGo Moment: When AI Rewrote 2,500 Years of Strategy

In 2016, an AI named AlphaGo made history. In a game of Go—a 2,500-year-old strategy game revered for its complexity—it executed a move no human had ever conceived. "The system was designed to always maintain a >50% chance of winning," explains Eric Schmidt, former Google CEO. "It invented something new." This moment, he argues, marked the quiet dawn of the AI revolution. While the public fixated on ChatGPT’s rise a decade later, insiders saw the seeds of transformation in AlphaGo’s ingenuity.

For Schmidt, this wasn’t just about games. It signaled AI’s potential to rethink problems humans believed they’d mastered. "How could a machine devise strategies billions of humans never imagined?" he asks. The answer lies in reinforcement learning—a paradigm where AI learns through trial, error, and reward. Today, systems like OpenAI’s "3o" or DeepSeek’s "R1" use this to simulate planning cycles, iterating solutions faster than any team of engineers. Schmidt himself uses AI to navigate complex fields like rocketry, generating deep technical papers in minutes. "The compute power behind 15 minutes of these systems is extraordinary," he notes.


AI’s Underhyped Frontier: From Language to Strategy

While ChatGPT dazzles with verbal fluency, Schmidt insists AI’s true potential lies beyond language. "We’re shifting from language models to strategic agents," he says. Imagine AI "agents" automating entire business processes—finance, logistics, R&D—communicating in plain English. "They’ll concatenate tasks, learn while planning, and optimize outcomes in real time," he explains.

But this requires staggering computational power. Training these systems demands energy equivalent to "90 nuclear plants" in the U.S. alone—a hurdle Schmidt calls "a major national crisis." With global rivals like China and the UAE racing to build 10-gigawatt data centers, the energy bottleneck threatens to throttle progress. Meanwhile, AI’s hunger for data has outpaced the public internet. "We’ve run out of tokens," Schmidt admits. "Now we must generate synthetic data—and fast."


The US-China AI Race: A New Cold War?

Geopolitics looms large. Schmidt warns of a "defining battle" between the U.S. and China over AI supremacy. While the U.S. prioritizes closed, secure models, China leans into open-source frameworks like DeepSeek—efficient systems accessible to all. "China’s open-source approach could democratize AI… or weaponize it," Schmidt cautions.

The stakes? Mutual assured disruption. If one nation pulls ahead in developing superintelligent AI, rivals may resort to sabotage. "Imagine hacking data centers or even bombing them," Schmidt says grimly. Drawing parallels to nuclear deterrence, he highlights the lack of diplomatic frameworks to manage AI-driven conflicts. "We’re replaying 1914," he warns, referencing Kissinger’s fear of accidental war. "We need rules before it’s too late."


Ethical Dilemmas: Safety vs. Surveillance

AI’s dual-use nature—beneficial yet dangerous—forces hard choices. Preventing misuse (e.g., bioweapons, cyberattacks) risks creating a surveillance state. Schmidt advocates for cryptographic "proof of personhood" without sacrificing privacy: "Zero-knowledge proofs can verify humanity without exposing identities."

He also stresses maintaining "meaningful human control," citing the U.S. military’s doctrine. Yet he critiques heavy-handed regulation: "Stopping AI development in a competitive global market is naive. Instead, build guardrails."


AI’s Brightest Promises: Curing Disease, Unlocking Physics, and Educating Billions

Despite risks, Schmidt radiates optimism. AI could eradicate diseases by accelerating drug discovery: "One nonprofit aims to map all ‘druggable’ human targets in two years." Another startup claims to slash clinical trial costs tenfold.

In education, AI tutors could personalize learning for every child, in every language. In science, it might crack mysteries like dark matter or revolutionize material science. "Why don’t we have these tools yet?" Schmidt challenges. "The tech exists—we lack economic will."


Humans in an AI World: Lawyers, Politicians, and Productivity Paradoxes

If AI masters "economically productive tasks," what’s left for humans? "We won’t sip piรฑa coladas," Schmidt laughs. Instead, he envisions a productivity boom—30% annual growth—driven by AI augmenting workers. Lawyers will craft "smarter lawsuits," politicians wield "slicker propaganda," and societies support aging populations via AI-driven efficiency.

Yet he dismisses universal basic income as a panacea: "Humans crave purpose. AI won’t eliminate jobs—it’ll redefine them."


Schmidt’s Advice: Ride the Wave

To navigate this "insane moment," Schmidt offers two mandates:

  1. Adopt AI or Become Irrelevant: "If you’re not using AI, your competitors are."

  2. Think Marathon, Not Sprint: "Progress is exponential. What’s impossible today will be mundane tomorrow."

He cites Anthropic’s AI models interfacing directly with databases—no middleware needed—as proof of rapid disruption. "This isn’t sci-fi. It’s happening now."


Conclusion: The Most Important Century

Schmidt calls AI "the most significant shift in 500 years—maybe 1,000." Its promise—curing disease, democratizing education—is matched only by its perils: geopolitical strife, existential risk. "Don’t screw it up," he urges. For Schmidt, the path forward hinges on ethical vigilance, global cooperation, and relentless innovation. "Ride the wave daily. This isn’t a spectator sport—it’s our future."


Tags: Technology,Artificial Intelligence,Agentic AI,Generative AI,

6 Months to Financial Freedom - A Step-by-Step Guide for Every Income Level


Lessons in Investing

Introduction
Whether you earn ₹15,000 or ₹1.5 lakh a month, financial freedom isn’t a myth—it’s a mindset. Over the next six months, this plan will transform how you manage money, eliminate debt, and build wealth, one small step at a time. No jargon, no shortcuts—just actionable strategies to reclaim control of your finances. Let’s begin.


Month 1: Face Your Finances (Stop the Ostrich Effect)

The Problem: We often bury our heads in the sand, ignoring bills, loans, and reckless spending.
The Fix: Track every expense—UPI payments, EMIs, cash spends—in real time. Use apps like ET Money, Walnut, or a simple Excel sheet.

Action Steps:

  1. Log Daily: Note every ₹17 spent. No exceptions.

  2. Categorize:

    • Needs: Rent, groceries, utilities.

    • Wants: Dining out, gadgets, vacations.

    • Investments: Future-focused spending (even if it’s ₹0 now).

  3. Analyze: By month-end, you’ll uncover surprises (“I spent HOW MUCH on Zomato?!”).

Why It Works: Awareness is the first step to control.


Month 2: Build Your Safety Net

The Analogy: Imagine a circus safety net. Your finances need one too.
The Goal: Save 1 month’s essential expenses. If your needs cost ₹20,000/month, save ₹20,000.

How:

  1. Trim Surprises: Cancel unused subscriptions (₹2,500 gym membership you haven’t touched).

  2. Temporarily Cut Wants: Skip impulse purchases for 1–2 months.

  3. Save Relentlessly: No, you won’t starve—this is a short-term hustle.

Outcome: A ₹20K buffer means you’re protected if income stops suddenly.


Month 3: Crush Bad Debt

The Reality: Debt is a silent dream-killer.
The Strategy:

  1. List All Debts: Credit cards, personal loans, EMIs.

  2. Separate Good vs. Bad Debt:

    • Good Debt: Education loans, home loans (assets that grow in value).

    • Bad Debt: Credit cards (35% interest!), luxury car loans (depreciating liabilities).

  3. Snowball Method: Pay off the smallest debt first. Celebrate each win—it builds momentum.

My Story: I cleared ₹50 lakh in loans over 12 years. Slow and steady works.


Month 4: Start Investing (Even ₹500 Matters)

The Basics:

  1. Automate Savings: EPF, PPF, NPS (safe but low returns).

  2. Index Funds: Invest in Nifty 50 or Nifty Next 50 via SIPs. Let experts manage the risk.

  3. Insurance:

    • Term Life Insurance: ₹1 crore cover for minimal premium.

    • Health Insurance: Separate policies for parents to avoid premium spikes.

Rule of Thumb:

  • 25 years old? Allocate 25% of investments to safe assets (gold, debt funds).

  • 40 years old? 40% to safe assets. The rest? Let the stock market grow your wealth.


Month 5: Boost Your Income

Mindset Shift: Cutting expenses has limits—earning potential doesn’t.
Ways to Earn More:

  1. Upskill: Learn AI/ML, coding, or freelancing.

  2. Side Hustles: Tutoring, consulting, selling digital products.

  3. Negotiate: Ask for a raise or switch jobs.

Example: A ₹10,000/month side gig = ₹1.2 lakh/year extra. Invest 50%, enjoy 50%.


Month 6: Automate Everything

The Goal: Remove willpower from the equation.
Steps:

  1. Auto-Pay Bills: Set up standing instructions for EMIs, SIPs.

  2. Invest First: Automate SIPs on payday—no temptation to spend.

  3. Track Digitally: Use apps for real-time visibility into cash flow.

Outcome: Money works for you while you sleep.


Conclusion: The Rich Mindset

True wealth isn’t about crores in the bank—it’s about control. After six months, you’ll:

  • Track every rupee.

  • Have zero bad debt.

  • Invest consistently.

  • Earn with purpose.

Final Truth: The “rich” aren’t lucky. They’re disciplined. Start today, and time will do the rest.


P.S. This plan is inspired by my own journey from ₹50 lakh in debt to financial freedom. If I did it, so can you. ๐Ÿš€

Tags: Investment,Video

Lessons in Investing


Toggle All Sections

Videos by Ankur Warikoo

Bitcoin

Nifty50

Stock Tips

survival8 Announcements

Miscellaneous

Tags: Investment,Management,Finance,

Thursday, May 15, 2025

Discussion on Cost of Balloons (Problem from HackerEarth)

To See All Articles About Technology: Index of Lessons in Technology
See the question on Hacker Earth
Difficulty: Easy

Problem

You are conducting a contest at your college. This contest consists of two problems and n participants. You know the problem that a candidate will solve during the contest.

You provide a balloon to a participant after he or she solves a problem. There are only green and purple-colored balloons available in a market. Each problem must have a balloon associated with it as a prize for solving that specific problem. You can distribute balloons to each participant by performing the following operation:

Use green-colored balloons for the first problem and purple-colored balloons for the second problem
Use purple-colored balloons for the first problem and green-colored balloons for the second problem
You are given the cost of each balloon and problems that each participant solve. Your task is to print the minimum price that you have to pay while purchasing balloons.

Input format

First line: T that denotes the number of test cases (1 <= T <= 10)
For each test case: 
First line: Cost of green and purple-colored balloons 
Second line: n that denotes the number of participants (1 <= n <= 10)

Next n lines: Contain the status of users. For example, if the value of the jth integer in the ith row is 0, then it depicts that the ith participant has not solved the jth problem. Similarly, if the value of the jth integer in the ith row is 1, then it depicts that the ith participant has solved the jth problem.
Output format
For each test case, print the minimum cost that you have to pay to purchase balloons.

Sample Input
2
9 6
10
1 1
1 1
0 1
0 0
0 1
0 0
0 1
0 1
1 1
0 0
1 9
10
0 1
0 0
0 0
0 1
1 0
0 1
0 1
0 0
0 1
0 0
Sample Output
69
14
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation
-

My Solution

T = int(input()) # num of test cases

for i in range(T):
    costs = input().split()
    costs = [int(c) for c in costs]

    min_cost = 0
    max_cost = 0
    if(costs[0] >= costs[1]):
        max_cost = costs[0]
        min_cost = costs[1]
    else:
        max_cost = costs[1]
        min_cost = costs[0]

    n = int(input()) # num of participants

    x_cnt = 0
    y_cnt = 0

    for j in range(n):
        status = input().split()
        if(status[0] == '1'):
            x_cnt += 1
        if(status[1] == '1'):
            y_cnt += 1

    if(x_cnt <= y_cnt):
        print(x_cnt * max_cost + y_cnt * min_cost)
    else:
        print(x_cnt * min_cost + y_cnt * max_cost)

Critique

Your solution works well and produces the correct output for the given problem. Let's evaluate it in terms of correctness, readability, and opportunities for improvement.


Problem Understanding (Recap)

Each participant may solve:

  • Problem 1: earns a balloon of one color.

  • Problem 2: earns a balloon of another color.

You can:

  • Assign green to problem 1 and purple to problem 2, or

  • Assign purple to problem 1 and green to problem 2.

The goal is to minimize the total cost of the balloons, depending on which problem participants solved and the balloon cost.


Correctness

Your code correctly:

  1. Reads costs and number of participants.

  2. Counts how many times each problem was solved (x_cnt, y_cnt).

  3. Chooses the cheaper mapping between balloon colors and problems.

It produces correct results for the provided test cases. ✅


๐Ÿ” Critique & Suggestions

1. ❌ Misleading variable naming: max_cost and min_cost

  • You’re not actually comparing costs to pick min/max based on which problem was solved more often.

  • What you should do is compute two total costs and pick the minimum.

Improvement: Calculate both options directly and pick the cheaper one.

python
T = int(input()) for _ in range(T): cost_g, cost_p = map(int, input().split()) n = int(input()) problem1 = 0 problem2 = 0 for _ in range(n): a, b = map(int, input().split()) problem1 += a problem2 += b # Option 1: green for problem1, purple for problem2 cost_option1 = problem1 * cost_g + problem2 * cost_p # Option 2: purple for problem1, green for problem2 cost_option2 = problem1 * cost_p + problem2 * cost_g print(min(cost_option1, cost_option2))

2. ๐Ÿ”„ Redundant logic for determining cheaper color

  • Your approach compares costs and conditionally assigns min_cost and max_cost, then compares counts, which is logically flawed in some edge cases.

Better to always calculate both cost combinations explicitly, as shown above.

3. ๐Ÿงผ Readability

  • Rename x_cntproblem1

  • Rename y_cntproblem2

It improves clarity and aligns with the problem.


๐Ÿงฎ Complexity Analysis

⏱ Time Complexity:

  • For each test case: O(n)

  • Total: O(T * n)

    • With T ≤ 10, n ≤ 10 → worst case = 100 lines = trivial runtime

๐Ÿง  Space Complexity:

  • O(1) (only counters and a few integers used)


✅ Summary

AspectRating / Comment
✅ Correctness✅ Works perfectly
❌ Efficiency✅ Fine due to low constraints
❌ ClarityVariable naming is misleading
❌ FlexibilityHardcoded min/max assignment logic is unnecessary
✅ ReadabilityCould be improved
✅ Suggested FixCompute both cost options and pick minimum

๐Ÿ”„ Final Suggestion: Use this simplified version

python
T = int(input()) for _ in range(T): cost_g, cost_p = map(int, input().split()) n = int(input()) problem1 = 0 problem2 = 0 for _ in range(n): a, b = map(int, input().split()) problem1 += a problem2 += b cost1 = problem1 * cost_g + problem2 * cost_p cost2 = problem1 * cost_p + problem2 * cost_g print(min(cost1, cost2))

Let me know if you’d like this converted to another language (e.g., C++ or Java) or want to add test case automation.

Tags: Technology,Algorithms,