Wednesday, May 14, 2025

Temple, Code, and the Quiet Pulse of Progress (2025-May-11)


Other Journaling Days

Morning: At dawn, I drove Akash, Chulbul, and Mahi to Tijara ji, a temple where silence drowns out life’s static. By 8 AM, we’d traded engine hum for incense, then returned to Gurugram’s chaos. Reality bit at the Maruti service center: an old parking lot scrape (courtesy of a rebellious pillar) now demanded insurance forms. Life stitches serenity with spreadsheets.

Afternoon: “What’s the one thing?” My blog nears 1.6M views—a milestone, but not the compass I crave. Yesterday, I coded, blogged, and laughed with Anu, jiju, and Mom. Rohit, ever the paradox, oscillated between genius and gibberish. Today, confusion lingers. Is this directionlessness or growth in disguise?

Post-Lunch: Routine rebels against inertia. I’ll code, skim a DeepLearning.AI course, and draft an AI blog post. Later, GitHub awaits—uploading interview code (fingers crossed). Nothing monumental, just the quiet work that builds futures.

The Lesson: Days like this—temples, repairs, and keystrokes—are life’s scaffolding. Clarity isn’t found in grand gestures but in showing up: for family calls, coding marathons, even parking lot oopsies.

Rohit’s nonsense? A reminder to laugh. The pillar? A metaphor: we all collide with obstacles, repair, and move forward.

Discusson about Zoos (Problem from HackerEarth)

To See All Articles About Technology: Index of Lessons in Technology
Try out on HackerEarth    
Difficulty: Easy

For this problem:

Problem
You are required to enter a word that consists of x and y that denote the number of Zs and Os respectively. The input word is considered similar to word zoo if 
2*x = y.

Determine if the entered word is similar to word zoo.

For example, words such as zzoooo and zzzoooooo are similar to word zoo but not the words such as zzooo and zzzooooo.

Input format

First line: A word that starts with several Zs and continues by several Os.
Note: The maximum length of this word must be 20.

Output format
Print Yes if the input word can be considered as the string zoo otherwise, print No.

Sample Input
zzzoooooo

Sample Output
Yes

I wrote the following code to solve the problem:

name=input()

var_z=0
var_o=0

var_z = name.count("z")
var_o = name.count("o")

if var_o == 2 * var_z:
    print("Yes")
else:
    print("No")

Can you critique my code and suggest any improvements or optimizations? Also, please provide a brief explanation of how the code works and any potential edge cases I should consider.

Your code is correct, concise, and easy to understand for the given problem. But let's go through a detailed critique, suggestions for improvements, and a review of possible edge cases.


✅ How Your Code Works

python
name = input() var_z = name.count("z") var_o = name.count("o") if var_o == 2 * var_z: print("Yes") else: print("No")

Explanation:

  • name.count("z") counts the number of 'z' characters → stored in var_z.

  • name.count("o") counts the number of 'o' characters → stored in var_o.

  • It then checks if var_o == 2 * var_z as per the condition in the problem.


✅ Pros

  • Correct logic: Accurately implements the 2 * z = o check.

  • Simple and readable: Easy to understand even for beginners.

  • Short and efficient: count() is a fast operation for small strings (within constraints).


🔍 Suggestions for Improvement

1. Check for invalid characters (input validation)

Right now, the code assumes that input will only contain z and o. It's good to validate that assumption:

python
if set(name) - {'z', 'o'}: print("Invalid input: Only 'z' and 'o' allowed.") else: ...

2. Use better variable names

Avoid var_z and var_o — use names that reflect meaning:

python
num_z = name.count('z') num_o = name.count('o')

3. Efficiency in very long strings

Although your approach is already efficient for normal input sizes, if the input is extremely large (e.g. 10^6 characters), you could avoid traversing the string twice:

python
num_z = num_o = 0 for ch in name: if ch == 'z': num_z += 1 elif ch == 'o': num_o += 1 else: print("Invalid input") exit()

This version processes the string once and handles invalid characters too.


⚠️ Edge Cases to Consider

InputExpected OutputNotes
zzooooYesStandard valid case
zzoooNoFails 2z = o
zooYes1z, 2o
zozoNoInvalid character order
zzzoooooNo3z vs 5o → 5 ≠ 6
zzzooooooYes3z vs 6o
zzzzzzNo6z vs 0o
ooooooNo0z vs 6o
Empty inputNoor handle as invalid
zOoNoCase-sensitive: 'O' ≠ 'o'

✅ Final Polished Version

python
name = input().strip() if set(name) - {'z', 'o'}: print("No") else: num_z = name.count('z') num_o = name.count('o') if num_o == 2 * num_z: print("Yes") else: print("No")

🧠 Summary

  • Your code works correctly and efficiently.

  • You can improve variable naming, optionally add input validation, and handle edge cases like mixed characters or casing.

  • For maximum robustness, scan the string once instead of using .count() twice — though for short strings it's not a concern.

Let me know if you want a version that reads from a file or handles multiple test cases!

Tags: Technology,Algorithms,

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,