Leetcode with dani
class Solution: def separateDigits(self, nums: List[int]) -> List[int]: return list(map(int,list(''.join(map(str,nums)))))
can u explain how this one line of code solves this question?
Leetcode with dani
The LeetCode problem "2553. Separate the Digits in an Array" requires transforming an array of positive integers into a new array containing each digit of those integers in the order they appear. Problem Denoscription: Given an array of positive integers nums…
can u solve with out changing to string?
Leetcode with dani
can u solve with out changing to string?
class Solution:
def separateDigits(self, nums: List[int]) -> List[int]:
result = []
for num in nums:
digits = []
while num > 0:
digits.append(num % 10) # Extract the last digit
num //= 10 # Remove the last digit
result.extend(digits[::-1]) # Reverse to maintain order
return result
▎LeetCode Problems with Solutions Easy Questions just to warm up😁
▎1. Fizz Buzz (Problem Link)
Problem Statement: Print numbers from 1 to n.
• If a number is divisible by 3, return "Fizz".
• If a number is divisible by 5, return "Buzz".
• If a number is divisible by both 3 and 5, return "FizzBuzz".
• Otherwise, return the number as a string.
Python Solution:
• Time Complexity: O(n)
• Space Complexity: O(n)
---
▎2. Pass the Pillow (Problem Link)
Problem Statement: n people sit in a circle, passing a pillow every second. The pillow starts at position 1. After a given amount of time, return the person who holds the pillow.
Python Solution:
• Time Complexity: O(1)
• Space Complexity: O(1)
---
▎3. Final Value of Variable After Performing Operations (Problem Link)
Problem Statement: Given an array of operations ("++X", "X++", "--X", "X--"), return the final value of X, starting from 0.
Python Solution:
• Time Complexity: O(n)
• Space Complexity: O(1)
---
▎4. Transformed Array (Problem Link)
Problem Statement: Modify an array by replacing each element with the sum of the absolute differences between it and its neighbors, until it stabilizes.
Python Solution:
• Time Complexity: O(n²) (worst case)
• Space Complexity: O(n)
---
▎5. Sum of Digits of String After Convert (Problem Link)
Problem Statement: Convert a string to digits (where a=1, b=2, ..., z=26), sum the digits, and repeat this process k times.
Python Solution:
• Time Complexity: O(n + k)
• Space Complexity: O(1)
https://news.1rj.ru/str/zethioprograming
▎1. Fizz Buzz (Problem Link)
Problem Statement: Print numbers from 1 to n.
• If a number is divisible by 3, return "Fizz".
• If a number is divisible by 5, return "Buzz".
• If a number is divisible by both 3 and 5, return "FizzBuzz".
• Otherwise, return the number as a string.
Python Solution:
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
return ["FizzBuzz" if i % 3 == 0 and i % 5 == 0 else
"Fizz" if i % 3 == 0 else
"Buzz" if i % 5 == 0 else str(i)
for i in range(1, n + 1)]
• Time Complexity: O(n)
• Space Complexity: O(n)
---
▎2. Pass the Pillow (Problem Link)
Problem Statement: n people sit in a circle, passing a pillow every second. The pillow starts at position 1. After a given amount of time, return the person who holds the pillow.
Python Solution:
class Solution:
def passThePillow(self, n: int, time: int) -> int:
cycle = (time % (2 * (n - 1)))
return n - abs(n - 1 - cycle)
• Time Complexity: O(1)
• Space Complexity: O(1)
---
▎3. Final Value of Variable After Performing Operations (Problem Link)
Problem Statement: Given an array of operations ("++X", "X++", "--X", "X--"), return the final value of X, starting from 0.
Python Solution:
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
return sum(1 if '+' in op else -1 for op in operations)
• Time Complexity: O(n)
• Space Complexity: O(1)
---
▎4. Transformed Array (Problem Link)
Problem Statement: Modify an array by replacing each element with the sum of the absolute differences between it and its neighbors, until it stabilizes.
Python Solution:
class Solution:
def transformedArray(self, arr: List[int]) -> List[int]:
while True:
new_arr = arr[:]
changed = False
for i in range(1, len(arr) - 1):
new_val = (arr[i-1] + arr[i+1]) // 2
if new_val != arr[i]:
new_arr[i] = new_val
changed = True
if not changed:
return arr
arr = new_arr
• Time Complexity: O(n²) (worst case)
• Space Complexity: O(n)
---
▎5. Sum of Digits of String After Convert (Problem Link)
Problem Statement: Convert a string to digits (where a=1, b=2, ..., z=26), sum the digits, and repeat this process k times.
Python Solution:
class Solution:
def getLucky(self, s: str, k: int) -> int:
num = ''.join(str(ord(c) - ord('a') + 1) for c in s)
for _ in range(k):
num = str(sum(int(d) for d in num))
return int(num)
• Time Complexity: O(n + k)
• Space Complexity: O(1)
https://news.1rj.ru/str/zethioprograming
👍2
▎1️⃣ Length of Last Word (Problem Link)
Problem: Given a string
Python Solution:
Problem: Given a string
s consisting of words separated by spaces, return the length of the last word. Python Solution:
class Solution:
def lengthOfLastWord(self, s: str) -> int:
return len(s.strip().split()[-1])
🟢 Time Complexity: O(n)
🟢 Space Complexity: O(1)
---
▎2️⃣ Find Three Consecutive Integers That Sum to a Given Number (Problem Link)
Problem: Find three consecutive integers whose sum equals num. If not possible, return an empty array.
Python Solution:
class Solution:
def sumOfThree(self, num: int) -> List[int]:
if num % 3 != 0:
return []
x = num // 3
return [x - 1, x, x + 1]
🟢 Time Complexity: O(1)
🟢 Space Complexity: O(1)
---
▎3️⃣ Rotate String (Problem Link)
Problem: Given two strings s and goal, check if s can become goal after some number of left rotations.
Python Solution:
class Solution:
def rotateString(self, s: str, goal: str) -> bool:
return len(s) == len(goal) and goal in (s + s)
🟢 Time Complexity: O(n)
🟢 Space Complexity: O(n)
---
👍2
https://leetcode.com/problems/rotate-string/
class Solution:
def rotateString(self, s: str, goal: str) -> bool:
if len(s) != len(goal):
return False
return goal in (s + s)
LeetCode
Rotate String - LeetCode
Can you solve this real interview question? Rotate String - Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.
A shift on s consists of moving the leftmost character of s to the rightmost position.…
A shift on s consists of moving the leftmost character of s to the rightmost position.…
if any one have good resources to learn programming and if u want to share u can send me with this bot @zprogramming_bot and i will share in this channel https://news.1rj.ru/str/techresourcesnew
▎Problem Title: Diagonal Traverse
▎Difficulty: Medium
▎Problem Statement:
Given an m x n matrix mat, return an array of all the elements of the matrix in a diagonal order.
▎Examples:
▎Example 1:
Input:
mat = [[1,2,3],
[4,5,6],
[7,8,9]]
Output:
[1,2,4,7,5,3,6,8,9]
▎Example 2:
Input:
mat = [[1,2],
[3,4]]
Output:
[1,2,3,4]
▎Constraints:
• m == mat.length
• n == mat[i].length
• 1 <= m, n <= 10^4
• 1 <= m * n <= 10^4
• -10^5 <= mat[i][j] <= 10^5
▎Notes:
• The output array should represent the elements of the matrix traversed in a diagonal pattern.
• Ensure that the function handles different matrix sizes and shapes correctly.
▎Difficulty: Medium
▎Problem Statement:
Given an m x n matrix mat, return an array of all the elements of the matrix in a diagonal order.
▎Examples:
▎Example 1:
Input:
mat = [[1,2,3],
[4,5,6],
[7,8,9]]
Output:
[1,2,4,7,5,3,6,8,9]
▎Example 2:
Input:
mat = [[1,2],
[3,4]]
Output:
[1,2,3,4]
▎Constraints:
• m == mat.length
• n == mat[i].length
• 1 <= m, n <= 10^4
• 1 <= m * n <= 10^4
• -10^5 <= mat[i][j] <= 10^5
▎Notes:
• The output array should represent the elements of the matrix traversed in a diagonal pattern.
• Ensure that the function handles different matrix sizes and shapes correctly.
LeetCode
Diagonal Traverse - LeetCode
Can you solve this real interview question? Diagonal Traverse - Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.
Example 1:
[https://assets.leetcode.com/uploads/2021/04/10/diag1-grid.jpg]
Input: mat =…
Example 1:
[https://assets.leetcode.com/uploads/2021/04/10/diag1-grid.jpg]
Input: mat =…
👍2
Leetcode with dani
▎Problem Title: Diagonal Traverse ▎Difficulty: Medium ▎Problem Statement: Given an m x n matrix mat, return an array of all the elements of the matrix in a diagonal order. ▎Examples: ▎Example 1: Input: mat = [[1,2,3], [4,5,6], [7,8,9]]…
class Solution:
def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]:
# Check for empty matrix
if not matrix or not matrix[0]:
return []
m, n = len(matrix), len(matrix[0])
result = []
row, col = 0, 0
# direction = 1 means moving up-right; direction = -1 means moving down-left.
direction = 1
while len(result) < m * n:
result.append(matrix[row][col])
if direction == 1: # Moving up-right.
# If we're at the last column, we can only go down.
if col == n - 1:
row += 1
direction = -1
# If we're at the top row, we can only go right.
elif row == 0:
col += 1
direction = -1
else:
row -= 1
col += 1
else: # direction == -1, Moving down-left.
# If we're at the bottom row, we can only go right.
if row == m - 1:
col += 1
direction = 1
# If we're at the first column, we can only go down.
elif col == 0:
row += 1
direction = 1
else:
row += 1
col -= 1
return result
💯5
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 all four directions (both the main diagonal and the anti-diagonal), and there is no limit to how far it can go in any diagonal direction. Note that the square where the bishop is placed is also counted in the sum.
Input:
The first number is an integer t, the number of test cases.
For each test case:
The first line contains two integers, n and m, representing the number of rows and columns.
This is followed by n lines, each containing m non-negative integers. These numbers are the values on the chessboard.
Output:
For each test case, output a single number: the maximum sum of the values from all the squares the bishop can attack when placed optimally on the board.
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 all four directions (both the main diagonal and the anti-diagonal), and there is no limit to how far it can go in any diagonal direction. Note that the square where the bishop is placed is also counted in the sum.
Input:
The first number is an integer t, the number of test cases.
For each test case:
The first line contains two integers, n and m, representing the number of rows and columns.
This is followed by n lines, each containing m non-negative integers. These numbers are the values on the chessboard.
Output:
For each test case, output a single number: the maximum sum of the values from all the squares the bishop can attack when placed optimally on the board.
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:
• Keep track of the maximum sum across all cells.
▎Complete Python Code
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
Please, join by the link https://codeforces.com/contests/2072?locale=en
Codeforces
Codeforces Round 1006 (Div. 3) - Codeforces
Codeforces. Programming competitions and contests, programming community
▎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
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:
Output: 2
Explanation: The entire array
Example 2:
Input:
Output: 2
Explanation: Either subarray
---
▎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
▎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.
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! 🚀
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! 🚀
akilconnect.org
Akil - Connecting talent with the right opportunities
Akil empowers Organizations to seamlessly post and manage opportunities, while connecting talent to personalized roles based on their preferences and skills.
👍3