Leetcode with dani – Telegram
Leetcode with dani
1.31K subscribers
197 photos
14 videos
56 files
240 links
Join us and let's tackle leet code questions together: improve your problem-solving skills
Preparing for coding interviews
learning new algorithms and data structures
connect with other coding enthusiasts
Download Telegram
Leetcode with dani
check out this question X-Sum Timur has a chessboard where each square contains a non-negative number. He wants to place a bishop on the board such that the sum of the numbers in all the squares it can attack is maximized. The bishop attacks diagonally in…
Key Idea

Precompute the sums for each diagonal and anti-diagonal to quickly calculate the bishop’s attack sum for any cell.

Breakdown

1. Diagonals Identification:

Main Diagonal (↘️): All cells share the same value of i - j (row index minus column index).

Anti-Diagonal (↙️): All cells share the same value of i + j (row index plus column index).

2. Precomputation:

• Iterate through the chessboard and sum up the values for:

• Each main diagonal (grouped by i - j ).

• Each anti-diagonal (grouped by i + j ).

3. Calculating the Bishop’s Sum:

• When placing the bishop on a cell (i, j) :

• It attacks all cells on the main diagonal (i - j) and the anti-diagonal (i + j) .

• Since the cell (i, j) is included in both diagonal sums, subtract its value once to avoid double counting.

4. Finding the Maximum Sum:

• For every cell, calculate the total sum as:

total = (sum on main diagonal) + (sum on anti-diagonal) - (value of cell)


• Keep track of the maximum sum across all cells.

Complete Python Code

def solve():
import sys
input = sys.stdin.readline

t = int(input())
for _ in range(t):
n, m = map(int, input().split())
board = [list(map(int, input().split())) for _ in range(n)]

diag_main = {} # Sums for main diagonal (i - j)
diag_anti = {} # Sums for anti-diagonal (i + j)

# Precompute the sums for both types of diagonals
for i in range(n):
for j in range(m):
d1 = i - j
d2 = i + j
diag_main[d1] = diag_main.get(d1, 0) + board[i][j]
diag_anti[d2] = diag_anti.get(d2, 0) + board[i][j]

max_sum = 0
# Evaluate maximum bishop sum for every possible cell placement
for i in range(n):
for j in range(m):
d1 = i - j
d2 = i + j
# Sum of both diagonals minus the overlapping cell (i, j)
total = diag_main[d1] + diag_anti[d2] - board[i][j]
if total > max_sum:
max_sum = total
print(max_sum)

if __name__ == "__main__":
solve()



▎Summary of the Approach in Simple Terms:

1. For each cell, determine which main and anti-diagonals it belongs to.

2. Sum all values on each diagonal.

3. For each cell, the bishop's attack sum equals the sum of its main diagonal plus the sum of its anti-diagonal, minus the cell’s own value (to correct for double counting).

4. Find the maximum of these sums over all cells.
👍3
Forwarded from Codeforces Official
Codeforces Round 1006 (Div. 3) will take place on the 25th of February at 14:35 UTC. 
Please, join by the link https://codeforces.com/contests/2072?locale=en
LeetCode Problem 525: Contiguous Array

Difficulty: Medium
Topics: Array, Hashing, Prefix Sum
Companies: Many top tech companies have featured similar problems in interviews
Link: Contiguous Array on LeetCode

---

Problem Statement

Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.

A contiguous subarray is one where the elements are consecutive, and an equal number of 0s and 1s means that the sum (after a transformation) is 0.

Note:

• You can transform the array by replacing each 0 with -1.

• Then, the problem reduces to finding the largest subarray whose sum is 0.

---

Examples

Example 1:
Input: nums = [0, 1]
Output: 2
Explanation: The entire array [0, 1] has one 0 and one 1.

Example 2:
Input: nums = [0, 1, 0]
Output: 2
Explanation: Either subarray [0, 1] or [1, 0] has an equal number of 0s and 1s.

---

Approach Explanation

1. Transform the Array:
Replace every 0 with -1. This way, a subarray with an equal number of 0s and 1s will have a total sum of 0.

2. Prefix Sum Hash Map:

Prefix Sum: Compute the cumulative sum while iterating through the transformed array.

Hash Map: Use a dictionary to store the first occurrence of each cumulative sum.

Finding a Subarray: If the same cumulative sum is seen again, the subarray between these two indices has a sum of 0 (equal number of 0s and 1s).

Update Maximum Length: Calculate the length of the subarray and update the maximum length if this subarray is longer.

3. Efficiency:
This approach works in O(n) time and O(n) space, making it efficient for large inputs.

---

Solution

def findMaxLength(nums):
# Replace 0 with -1 for transformation
for i in range(len(nums)):
if nums[i] == 0:
nums[i] = -1

cumulative_sum = 0
max_length = 0
sum_index_map = {} # To store the first occurrence of each cumulative sum

for i, num in enumerate(nums):
cumulative_sum += num

# Check if cumulative_sum is 0, which means subarray from index 0 to i is valid
if cumulative_sum == 0:
max_length = i + 1

# If cumulative_sum has been seen before, update max_length accordingly
if cumulative_sum in sum_index_map:
max_length = max(max_length, i - sum_index_map[cumulative_sum])
else:
sum_index_map[cumulative_sum] = i

return max_length

# Testing the function with provided examples
print(findMaxLength([0, 1])) # Output: 2
print(findMaxLength([0, 1, 0])) # Output: 2

▎Final Recap

This solution transforms the binary array into one that uses -1 instead of 0, so that we can use the cumulative sum to detect subarrays with equal numbers of 0s and 1s. By maintaining a hash map of the first occurrence of each cumulative sum, we can efficiently calculate the maximum length of any subarray with a sum of 0. This is a neat and efficient way to tackle the problem!

For more details, visit the problem link: Contiguous Array on LeetCode.
👍2
Leetcode with dani
▎LeetCode Problem 525: Contiguous Array Difficulty: Medium Topics: Array, Hashing, Prefix Sum Companies: Many top tech companies have featured similar problems in interviews Link: Contiguous Array on LeetCode --- ▎Problem Statement Given a binary…
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
s = {0:-1}
t = 0
maxm = 0
c1 = 0
c0 = 0
for i in range(len(nums)):
if nums[i]:
c1+=1
else:
c0+=1
if c1-c0 not in s:
s[c1-c0] = i
else:
maxm = max(maxm,i-s[c1-c0])
return maxm
🚀 A2SV Internship Program – Level Up Your Tech Skills! 🚀

Gain hands-on experience in Frontend, Backend, Mobile Development, UI/UX, and Product Management while working on real projects with industry experts. Perfect for students looking to grow and launch their tech careers!

📌 Requirements: Must be a continuing student in their internship phase and have completed or be enrolled in A2SV’s G6 program.

📍 Location: Abrehot Library (In-person)
Hours: 9 AM - 12 PM, 2 PM - 6 PM (G6: 2 PM - 4 PM)

Apply now and start your journey with A2SV! 🚀
👍3
Leetcode with dani
https://leetcode.com/problems/remove-linked-list-elements/ Easy question for beginner to linked list
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
dummy = ListNode(0,head)
p1 = dummy
p2 = dummy.next
while p2:
if p2.val==val:
p1.next = p2.next
p2 = p2.next
else:
p1 = p1.next
p2 = p2.next
return dummy.next
Leetcode with dani
https://leetcode.com/problems/remove-nth-node-from-end-of-list/
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy = ListNode(-1,head)
p1 = dummy
p2 = dummy.next
count = 0
while p2:
if count <n:
p2 = p2.next
count+=1
else:
p1 = p1.next
p2 = p2.next
if p1:
p1.next = p1.next.next
return dummy.next
Leetcode with dani
https://leetcode.com/problems/middle-of-the-linked-list/denoscription/
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
p1 = head
p2 = head
while p2 and p2.next:
p1=p1.next
p2 = p2.next.next
return p1
Did you understand Floyd’s Cycle-Finding Algorithm for Linked List? It’s pretty cool and clever!
👌3
Top 10 Non-Technical Interview Questions for FAANG Companies: Insights and Preparation Tips

🧠 Behavioral Leadership

1. "Tell me about a time you failed and what you learned."
Tests self-awareness and growth mindset.

2. "Describe a team conflict you resolved."
Assesses emotional intelligence and mediation skills.

3. "Share an example of showing leadership without authority."
Evaluates initiative and influence.

🎯 Career Motivation

4. "Why do you want to work here specifically?"
Probes company research and cultural fit.

5. "Where do you see yourself in 3-5 years?"
Checks alignment with company growth paths.

🌟 Strengths Values

6. "What unique value would you bring to this team?"
Reveals self-assessment accuracy.

7. "Describe your most innovative professional contribution."
Assesses creativity and business impact.

🛠 Work Approach

8. "How do you prioritize when facing multiple deadlines?"
Tests organizational and decision-making skills.

9. "Tell me about a project requiring deep analysis."
Examines problem-solving methodology.

🤝 Cultural Fit

10. "What does ideal team collaboration look like to you?"
Matches working style with company culture.

---

▎Key Preparation Tips:

• Use the STAR (Situation-Task-Action-Result) format for behavioral answers.

• Align responses with FAANG leadership principles.

• Practice concise storytelling (90-120 seconds per answer).

• Research specific company values (e.g., Amazon's 16 Leadership Principles).

For 53 additional common questions and answer frameworks, refer to:
FAANG Behavioral Guide (https://igotanoffer.com/blogs/tech/faang-interview-questions)
Non-Technical Question Strategies (https://www.indeed.com/career-advice/interviewing/non-tech-interview-questions)
🔥2