Wednesday, May 14, 2025

Discussion about Maximum Border (Problem from HackerEarth)

To See All Articles About Technology: Index of Lessons in Technology
Try out the problem here.

This is the problem:

Difficulty: Easy
Problem

You are given a table with n rows and m columns. Each cell is colored with white or black. Considering the shapes created by black cells, what is the maximum border of these shapes? Border of a shape means the maximum number of consecutive black cells in any row or column without any white cell in between.

A shape is a set of connected cells. Two cells are connected if they share an edge. Note that no shape has a hole in it.

Input format

The first line contains t denoting the number of test cases.
The first line of each test case contains integers n and m denoting the number of rows and columns of the matrix. Here, '#' represents a black cell and '.' represents a white cell. 
Each of the next n lines contains m integers.

Output format
Print the maximum border of the shapes.


Based on these examples:

Print the maximum border of the shapes.

Sample Input
10
2 15
.....####......
.....#.........
7 9
...###...
...###...
..#......
.####....
..#......
...#####.
.........
18 11
.#########.
########...
.........#.
####.......
.....#####.
.....##....
....#####..
.....####..
..###......
......#....
....#####..
...####....
##.........
#####......
....#####..
....##.....
.#######...
.#.........
1 15
.....######....
5 11
..#####....
.#######...
......#....
....#####..
...#####...
8 13
.....######..
......##.....
########.....
...#.........
.............
#######......
..######.....
####.........
7 5
.....
..##.
###..
..##.
.....
..#..
.#...
14 2
..
#.
..
#.
..
#.
..
..
#.
..
..
..
#.
..
7 15
.###########...
##############.
...####........
...##########..
.......#.......
.....#########.
.#######.......
12 6
#####.
###...
#.....
##....
###...
......
.##...
..##..
...#..
..#...
#####.
####..
Sample Output
4
5
9
6
7
8
3
1
14
5



I have written this psuedocode to solve the problem:

1. I will track if I observe a number. And when I do, I would read it (let's say) "2 15" to take out the 2 and 15.
2. Then I will start a loop for the number of times I observed as the first number.
3. Then I will count the hashes in the those lines on which I will iterate in step 2.
4. I will maintain a max_border variable to keep track of the maximum number of hashes (in a border) I have seen so far.

Would it work? Is it optimized?

Thanks for the detailed examples. I reanalyzed the problem using the sample inputs and outputs, and you’re absolutely right to ask for a recheck.


✅ Problem Clarified (Based on Samples)

You're not being asked to detect connected shapes. You're asked for:

The maximum number of consecutive black cells (#) in any row or column across the entire matrix.

So, the concept of shapes and connectivity is a red herring — you're not required to group connected components.


✅ Actual Requirement (Based on Examples):

Given a grid of R x C, for each test case:

  • Find the longest sequence of # in any row or any column.

  • That sequence can be anywhere in the grid.

  • You're not restricted to connected components at all.

  • So no DFS/BFS is needed.


✅ Corrected and Optimized Approach

  1. Loop through every row:

    • Count max number of consecutive #s.

  2. Loop through every column:

    • Count max number of consecutive #s.

  3. Take the maximum from both row-wise and column-wise streaks.


✅ Python Code Implementation

python
def max_border(grid, R, C): max_streak = 0 # Check row-wise for row in grid: count = 0 for cell in row: if cell == '#': count += 1 max_streak = max(max_streak, count) else: count = 0 # Check column-wise for col in range(C): count = 0 for row in range(R): if grid[row][col] == '#': count += 1 max_streak = max(max_streak, count) else: count = 0 return max_streak # Driver code T = int(input()) for _ in range(T): R, C = map(int, input().split()) grid = [input().strip() for _ in range(R)] print(max_border(grid, R, C))

✅ Time and Space Complexity

  • Time Complexity: O(R × C)

  • Space Complexity: O(1) (excluding input)


✅ Summary

QuestionAnswer
Do we need DFS/BFS?❌ No. Shapes are irrelevant.
Are cells part of the same shape?❌ Not required to check.
What matters?✅ Longest consecutive #s in row or column
Your initial approach?✅ Partially valid — just needs column check

Let me know if you'd like a version in another language (C++/Java).

Can you compare this (my) code with your code:

import re

data = []

t = int(input())
data.append(t)

for i in range(t):

    nm = input() 
    data.append(nm)

    # nm is of the form "2 2", "3 4", "7 3", "11 6", "3 12", "12 13" etc.

    nm = nm.split()

    # Now nm contains a list of string representation of two integers.

    """ 
    # Multiline comment
    nm2 = []

    for i in nm:
        nm2 = int(i)
    """

    nm2 = [int(i) for i in nm]

    #print(nm2)

    for j in range(nm2[0]):
        row = input() # This is just dots and hashes
        data.append(row)



# Processing the input
# Producing indices of where tables are located in the input data.
# [[2, 4], [5, 12], [13, 31], ...] This is what will be produced
# i would contain [2, 4], then [5, 12], then [13, 31], so on and so forth

input_idx = []

for i in range(len(data)):
    if i == 0:
        # At the line 0: we are having the number representing count of input. We have to skip the first line only.
        continue 

    if re.match(r'^[0-9]', data[i]): 
        # If my line starts with a digit
        # ^ 	Starts with
        # [0-9] Returns a match for any digit between 0 and 9

        idx = []

        idx.append(i + 1)

        num_rows = data[i].split()[0]
        # Range is coming in the form of: num_rows num_cols
        # So we spliting on whitespace and extracting the zeroth element

        idx.append(i + 1 + int(num_rows))
        # i + 1: represents the start. So what would be our end: start + num_rows

        input_idx.append(idx)

# ~~~ Processing input ~~~ ends here

for i in input_idx:
    # [[2, 4], [5, 12], [13, 31], ...] This is what is coming as input_idx
    # i would contain [2, 4], then [5, 12], then [13, 31], so on and so forth

    pattern = data[i[0] : i[1]]

    num_hashes = []
    for j in pattern:
        num_hashes.append(j.count('#'))
    
    print(max(num_hashes))

Your code is logically valid and works for the provided problem — it produces correct output. However, let’s compare your code and my earlier version in terms of:


✅ 1. Correctness

AspectYour CodeMy Code
Counts # in rows✅ Yes✅ Yes
Counts # in columnsNo (Missing)Yes
Uses max streak❌ Only counts total per row✅ Counts consecutive #s only

🔴 Your code outputs the row with the most number of #, not the longest streak of consecutive #.
✅ My code counts the maximum consecutive #s (which matches the sample output).


✅ 2. Functionality Example

Let’s consider this input row:

txt
.#.###.##.
  • Your code: row.count('#') = 5 (correct total count)

  • Problem asks: What is the longest consecutive #s? → Here, it’s 3 (###)

So your code would return 5 as the max for this row, but the correct border is 3.

✅ My code uses a loop to track streaks → correct.


✅ 3. Column Streaks

  • Your code processes only rows.

  • It completely misses column-wise streaks like this:

text
#..# #..# #..#

→ This has a vertical streak of 3 #s, but your code would return 1 for each row.

✅ My code checks columns as well.


✅ 4. Structure / Complexity Comparison

AspectYour CodeMy Code
Code LengthLonger due to custom indexingShorter and more direct
ReadabilityMedium (manual tracking of ranges)Higher (uses functions, less manual parsing)
PreprocessingManual index trackingReads grid row-by-row
Regex usageFor identifying numeric linesNot needed
Column support❌ Missing✅ Present
Streak logic❌ Missing (uses total counts)✅ Tracks streaks

✅ 5. Time and Space Complexity

Let R = rows, C = columns, T = test cases

Your Code:

  • Time: O(T × R × C)

    • Because for each test case, you count #s in each row (O(C))

  • Space: Stores all input → O(T × R × C)

  • ✅ Efficient in row processing

  • ❌ Misses column and streak logic

My Code:

  • Time: O(T × R × C)

    • Processes both rows and columns fully

  • Space: O(R × C) per test case

  • ✅ Slightly more thorough but same order complexity


✅ Summary Table

FeatureYour CodeMy Code
Row-wise streaks❌ (total count)
Column-wise streaks
Matches problem statement?
Regex usage✅ (for parsing)
Code structureManualModular

✅ Final Verdict

  • Your code is clever in parsing input with regex and tracking blocks.

  • However, for the actual problem requirement (finding max consecutive #s in row or column), it's functionally incomplete.

  • My code is more aligned with the intended logic and gives the correct results as per sample outputs.


Would you like me to help you extend your code to support streaks and columns (instead of rewriting from scratch)?

Does this algo sounds complete:

1. I will track if I observe a number. And when I do, I would read it (let's say) "2 15" to take out the 2 and 15.
2. Then I will start a loop for the number of times I observed as the first number.
3. Then I will count the hashes in the those lines on which I will iterate in step 2.
4. I will maintain a max_border variable to keep track of the maximum number of hashes appearing continuously (in a border) I have seen so far.
5. Next, we will iterate through the columns and count the hashes in the same way as we did for the rows.
6. Just one clarity about step 5: we would need to load the entire dots-and-hashes matrix into a 2D array and then iterate through it column-wise to count maximum number of continuously appearing hashes.

Yes — your revised algorithm now sounds complete and correct for solving the "maximum border of black cell shapes" problem as intended. Let's break it down to confirm each step:


✅ Your Algorithm Breakdown

Step 1:

Track when a line like "2 15" appears, and extract 2 (rows) and 15 (columns).

  • ✔️ Correct — this lets you know how many lines to read next as the matrix.


Step 2:

Loop for the number of times as the row count.

  • ✔️ Correct — this helps read the full grid for the current test case.


Step 3:

Count the hashes (#) in each of those lines.

  • ⚠️ Slight correction: don't just count total #.

  • ✅ You should find the maximum streak of consecutive #s in the row — that's what the problem wants.

Example:
..###.#..# → has total 5 #, but maximum consecutive #s = 3
So you need to process each row using a loop like:

python
max_row_streak = 0 count = 0 for cell in row: if cell == '#': count += 1 max_row_streak = max(max_row_streak, count) else: count = 0

Step 4:

Maintain max_border to track the largest such streak.

  • ✔️ This is correct — initialize to 0 and update as needed.


Step 5:

Iterate column-wise and repeat the same process as step 3.

  • ✔️ This is essential and was missing in your earlier version, so great job adding it.


Step 6:

To iterate column-wise, store the matrix in a 2D array.

  • ✔️ Absolutely correct — to access columns, you need all rows first.

Example loop:

python
for col in range(num_cols): count = 0 for row in range(num_rows): if matrix[row][col] == '#': count += 1 max_border = max(max_border, count) else: count = 0

✅ Final Verdict

CriteriaStatus
Handles rows correctly?
Handles columns correctly?
Tracks max consecutive hashes?
Matrix storage for column scan?
Matches sample outputs?
Optimized and simple?

✅ Conclusion

Your updated algorithm is complete and well-reasoned. With careful implementation of row and column streak checks, it will solve the problem correctly and efficiently.

Let me know if you'd like a Python implementation based on this plan!

Tags: Technology,Algorithms,

Silicon Valley is ready for a makeover: Why time is running out for iPhone, Google Search and Facebook

All About Management

Silicon Valley makeover.

The Silicon Valley 'product companies' have acknowledged that the iPhone, Google Search, and Facebook might not exist in the next few years. If someone asks you about the common thread among the iPhone, Google Search, and Facebook, it’s that all three have changed the tech landscape, and have lasted far longer than the average product. The iPhone debuted in 2007, Google in 1998, and Facebook in 2004. All three tech giants and their core products still dominate the market, generate billions of dollars each year, and have made average consumers dependent on them in everyday life. But in recent weeks, the ongoing antitrust trials against Google and Meta have revealed that the success of the iPhone, Google Search, and Facebook may be numbered—and that each of these hit products, which once changed the course of tech, could soon be replaced. Silicon Valley makeover. Apple is still searching for the next big thing after the iPhone, and in recent years, the company has internally axed many projects, including the high-profile autonomous self-driving car. Truth be told, Facebook is no longer used by the cool, trendy younger demographic, the iPhone feels mature, the pace of innovation has slowed, and Google Search is in decline while AI chatbots like ChatGPT and Google’s own Gemini continue to grow. What might replace the iPhone remains unknown — a mixed-reality headset, a pair of smart glasses, or perhaps a touchscreen-less gadget. But it’s evident that Apple is preparing for a future where a new device could eventually replace the iPhone and the existing mobile ecosystem. Then again, whatever replaces the iPhone might not come from Apple at all — it could be built by a company we haven’t even heard of yet. Cue, a high-profile tech executive, like many others, sees artificial intelligence as the core of future devices that may eventually replace traditional smartphones like the iPhone. In fact, he calls AI a “huge technological shift” and suggests that such tectonic changes can give rise to new companies while making old ones irrelevant. Cue didn’t mean that the iPhone is going away right now — not at all. Apple is rumoured to be working on multiple iPhone models internally, including an ultra-slim iPhone expected to launch later this year, as well as a foldable iPhone and a model with an edge-to-edge display that could hit the market in the next three to four years. However, one cannot deny that the iPhone is built on ageing technology. While it may just be gaining popularity in developing markets like India, the iPhone has already peaked in mature markets such as the US and Europe. There’s no doubt that Apple still sells millions of iPhones each year, but growth has slowed — a clear sign that the iPhone era may be nearing its peak. Google vs AI search engines But the iPhone isn’t the only product headed for maturity; Google Search is another service we may not need to rely on in the future. The reason? The increasing adoption of OpenAI’s ChatGPT, Google Gemini, and Perplexity. Google pays Apple billions of dollars per year (to the tune of $20 billion) to be the default search engine on iPhones. It’s a win-win for both Apple and Google, with the latter gaining search volume and users. But when Cue recently made comments that AI search engines will eventually replace traditional search engines like Google, it caused Alphabet’s shares to drop more than 7 per cent, wiping off $200 billion from the company’s market value. Google Search is still the default way people search the Internet, powered by its proprietary ‘Knowledge Graph’ database — and there is currently no true alternative to it. But with OpenAI now aggressively adding and improving search capabilities in ChatGPT, which now has 400 million weekly users, the industry is beginning to see a shift toward AI chatbots for general search, potentially overtaking traditional search engines like Google in the near future. Market research firm Gartner estimated last year that search engine volume could drop by 25 per cent by 2026, as more users shift to AI-based tools for search. Google currently controls 90 per cent of the search market, and search engine optimisation (SEO) remains central to how websites boost their visibility on the platform. But many are now questioning whether Google is still as useful as it once was. Ads and algorithm tweaks have made search more complex, pushing some users away from Google and putting pressure on the company that made web search accessible to billions. Google, however, has denied that overall growth in search volume is declining. In a statement last week, the Mountain View, California-based company said it continues “to see overall query growth in Search,” including “an increase in total queries coming from Apple’s devices and platforms.” The statement appeared to be an effort to protect its lucrative advertising business, which brings billions of dollars annually. Meta (formerly Facebook) is also at a crossroads due to the declining popularity of Facebook, the social network created by Mark Zuckerberg, which is now facing an external crisis fuelled by the global rise of TikTok and Meta’s own Instagram. “The amount that people are sharing with friends on Facebook, especially, has been declining,” Zuckerberg said in April during an antitrust lawsuit brought by the Federal Trade Commission. “Even the amount of new friends that people add … I think has been declining. But I don’t know the exact numbers.” The perception that young users still use Facebook no longer exists — a reality that Mark Zuckerberg himself has acknowledged. But the question remains: if not Facebook, where are users flocking to? The answer is TikTok and Instagram. Ironically, TikTok is not a traditional social network; it’s an app, which has taken the world by storm, which hosts short-form user videos and is owned by the Chinese company ByteDance. Facebook is in the past, and while Zuckerberg did try to create a new type of social network in the form of the Metaverse, it never had the same impact that Facebook did in the early 2010s. Next big players All three tech giants, Apple, Google, and Meta, are still figuring out what will replace their star products. The iPhone remains the most popular smartphone on the market, and there is no true alternative to it. Google Search continues to be a lifeline for billions when it comes to searching for information on the internet. While Facebook is in decline, the concept of social networks has evolved over the years, and it’s unclear if the world even needs another social network anymore. The shift is already happening, as OpenAI and Nvidia are becoming the next big players in the tech space, potentially changing the tech landscape in the same way Apple, Google, and Meta once did. All three of these companies are now on the radar of regulators, facing accusations of malpractice and questionable business models that have stifled smaller players. But as technology constantly evolves and consumer behaviour shifts, with emerging technologies like AI becoming the frontrunners, Silicon Valley is ready for a makeover. Ref
Tags: Technology,Management,Investment,

Layoffs sweep tech industry, more than 50,000 lose their jobs so far in 2025 (Reported in May)

To See All Articles About Layoffs: Layoffs Reports
Layoffs sweep tech industry, more than 50,000 lose their jobs so far in 2025

Layoffs have swept through the tech sector during the first few months of 2025 — with more than 50,000 people losing their jobs.

According to data from layoffs.fyi, more than 53,100 workers from 126 tech companies have been affected during the first five months of the year. Intel led the list with recent reports suggesting that company planned to fire around 20% of its workforce in a matter of days. The announcement came months after the struggling chipmaker laid off around 15,000 people. Intel had later denied the claims — contending that layoffs would begin in the second quarter of 2025 and continue across several months.

Meanwhile European battery manufacturer Northvolt fired around half its staff (2800 people) at the end of March — weeks after filing for bankruptcy. The Swedish company had previously announced plans to fire around 1600 employees in September last year.

Mark Zuckerberg-led Meta featured prominently on the list, with the layoff tracker website indicating that around 4000 employees had lost their jobs since 2025 began.

Google had also made an unspecified number of cuts in its various divisions during the month of February — offering buyouts to many US-based employees. Reports in mid-April indicated that the company had laid off hundreds of employees within its platforms and devices unit in a bid to streamline jobs and become more ‘nimble’. The layoffs in April came in addition to the voluntary exit program that began in January.

Ref

Saturday, May 10, 2025

Discussion about Favourite Singer (Problem from HackerEarth)

To See All Articles About Technology: Index of Lessons in Technology
Try out the problem here

Problem

Bob has a playlist of N songs, each song has a singer associated with it (denoted by an integer)

Favourite singer of Bob is the one whose songs are the most on the playlist

Count the number of Favourite Singers of Bob

Input Format 

The first line contains an integer N, denoting the number of songs in Bob's playlist.

The following input contains N integers, ith integer denoting the singer of the ith song.

Output Format

Output a single integer, the number of favourite singers of Bob

Note: Use 64 bit data type

Constraints
N <= 2*10^5
a[i] <= 10^15

Sample Input
5
1 1 2 2 4

Sample Output
2

Let's break this down and then provide a clear and efficient solution.


Problem Summary

  • You're given a list of integers representing singers for each song in Bob's playlist.

  • A favourite singer is one who has the maximum number of songs in the playlist.

  • You need to count how many singers have that maximum number of songs.


Approach

  1. Use a dictionary (or collections.Counter) to count how many songs each singer has.

  2. Find the maximum song count from this dictionary.

  3. Count how many singers have this maximum count.


Python Code

python
def count_favourite_singers(n, singers): from collections import defaultdict singer_count = defaultdict(int) # Step 1: Count songs for each singer for singer in singers: singer_count[singer] += 1 # Step 2: Find maximum count max_count = max(singer_count.values()) # Step 3: Count how many singers have that max count favourite_count = sum(1 for count in singer_count.values() if count == max_count) return favourite_count

Input/Output Handling

python
# Read input n = int(input()) singers = list(map(int, input().split())) # Compute and print the result print(count_favourite_singers(n, singers))

Time and Space Complexity

  • Time Complexity: O(n) – one pass to count, one pass to find max and count again.

  • Space Complexity: O(k) – where k is the number of unique singers.


Would you like a C++ or Java version too, since this might be used in a competitive programming context?




Can you do a comparison of your code with this code:

from collections import Counter

N = int(input())
l = [int(i) for i in input().split()]

most_common = Counter(l).most_common()

favorite_count = most_common[0][1]

m = [i for i in most_common if i[1] == favorite_count]

print(len(m))

Absolutely — let’s compare your code using Counter.most_common() with my code using defaultdict.


🔍 Code Comparison: Side by Side

Your Code

python
from collections import Counter N = int(input()) l = [int(i) for i in input().split()] most_common = Counter(l).most_common() # List of (singer, count) sorted descending favorite_count = most_common[0][1] # Get the max count m = [i for i in most_common if i[1] == favorite_count] # Filter singers with max count print(len(m)) # Count them

My Code

python
from collections import defaultdict def count_favourite_singers(n, singers): singer_count = defaultdict(int) for singer in singers: singer_count[singer] += 1 max_count = max(singer_count.values()) favourite_count = sum(1 for count in singer_count.values() if count == max_count) return favourite_count # Input handling n = int(input()) singers = list(map(int, input().split())) print(count_favourite_singers(n, singers))

✅ Key Differences

FeatureYour Code (Counter)My Code (defaultdict)
LibraryUses Counter.most_common()Uses manual counting with defaultdict
Sorting StepYes.most_common() returns a sorted listNo – avoids sorting
Time ComplexityO(n log n) due to sortingO(n) — more efficient
Space ComplexityO(k) for storing countsO(k) as well
ReadabilityShort and conciseSlightly more verbose, but very clear
FlexibilityLess general (tied to sorting order)More general and customizable

⏱️ Efficiency Note

The biggest difference is:

  • Counter.most_common() sorts the entire count dictionary, which takes O(k log k) time, where k is the number of unique singers.

  • My version finds the max and counts how many times it occurs in O(k) time without sorting.

In large datasets (e.g. 10⁶ songs, 10⁵ singers), my version is faster because it avoids sorting altogether.


🏁 Final Verdict

Use CaseRecommended Code
Small input (e.g. coding contest)Your code (short & clean)
Large input / time-sensitiveMy code (no sort, O(n))
Readability / beginner-friendlyMy code (step-by-step)

Would you like me to rewrite your version to avoid sorting but keep it just as concise?

Tags: Technology,Algorithms,