Leetcode with dani
Problem Statement Write a function int_to_roman(num: int) -> str that converts an integer (1 to 3999) to its Roman numeral representation. The Roman numeral system uses the following symbols: • I = 1 • V = 5 • X = 10 • L = 50 • C = 100 • D = 500 •…
▎Approach 1: Greedy Algorithm
▎Approach 2: Using a Dictionary
▎Approach 3: Recursive Method
▎Summary of Approaches
1. Greedy Algorithm: This approach involves repeatedly subtracting the largest possible Roman numeral value from the integer until the number is reduced to zero.
2. Using a Dictionary: Similar to the greedy approach but utilizes a dictionary to map values to their Roman numeral representations for clarity.
3. Recursive Method: This approach uses recursion to build the Roman numeral string by checking against the mapping and reducing the number accordingly.
class Solution:
def intToRoman(self, num: int) -> str:
# Define the mapping of integers to Roman numerals
val = [
1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4,
1
]
syms = [
"M", "CM", "D", "CD",
"C", "XC", "L", "XL",
"X", "IX", "V", "IV",
"I"
]
roman_num = ''
i = 0
while num > 0:
for _ in range(num // val[i]):
roman_num += syms[i]
num -= val[i]
i += 1
return roman_num
# Example usage:
sol = Solution()
print(sol.intToRoman(1994)) # Output: "MCMXCIV"
▎Approach 2: Using a Dictionary
class Solution:
def intToRoman(self, num: int) -> str:
# Mapping of integer values to Roman numerals
roman_map = {
1000: 'M',
900: 'CM',
500: 'D',
400: 'CD',
100: 'C',
90: 'XC',
50: 'L',
40: 'XL',
10: 'X',
9: 'IX',
5: 'V',
4: 'IV',
1: 'I'
}
roman_numeral = ''
for value in roman_map.keys():
while num >= value:
roman_numeral += roman_map[value]
num -= value
return roman_numeral
# Example usage:
sol = Solution()
print(sol.intToRoman(58)) # Output: "LVIII"
▎Approach 3: Recursive Method
class Solution:
def intToRoman(self, num: int) -> str:
# Define the mapping of integers to Roman numerals
roman_map = [
(1000, 'M'),
(900, 'CM'),
(500, 'D'),
(400, 'CD'),
(100, 'C'),
(90, 'XC'),
(50, 'L'),
(40, 'XL'),
(10, 'X'),
(9, 'IX'),
(5, 'V'),
(4, 'IV'),
(1, 'I')
]
def convert(n):
if n == 0:
return ""
for value, symbol in roman_map:
if n >= value:
return symbol + convert(n - value)
return convert(num)
# Example usage:
sol = Solution()
print(sol.intToRoman(3)) # Output: "III"
▎Summary of Approaches
1. Greedy Algorithm: This approach involves repeatedly subtracting the largest possible Roman numeral value from the integer until the number is reduced to zero.
2. Using a Dictionary: Similar to the greedy approach but utilizes a dictionary to map values to their Roman numeral representations for clarity.
3. Recursive Method: This approach uses recursion to build the Roman numeral string by checking against the mapping and reducing the number accordingly.
Leetcode with dani
▎Approach 1: Greedy Algorithm class Solution: def intToRoman(self, num: int) -> str: # Define the mapping of integers to Roman numerals val = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, …
Solution 4: Digit-by-Digit Using a Dictionary
This method converts the number to a string and processes each digit individually. It uses a dictionary to map base values and computes the appropriate power of ten for each digit. The solution handles subtractive cases (i.e., when a digit is 4 or 9) separately.
This method converts the number to a string and processes each digit individually. It uses a dictionary to map base values and computes the appropriate power of ten for each digit. The solution handles subtractive cases (i.e., when a digit is 4 or 9) separately.
class Solution:
def intToRoman(self, num: int) -> str:
roman = {1: "I", 5: "V", 10: "X", 50: "L", 100: "C", 500: "D", 1000: "M"}
s = ""
st = str(num)
length = len(st)
for ch in st:
i = int(ch)
# Calculate the current power of ten (e.g., 1000, 100, 10, 1)
place = 10 ** (length - 1)
if i == 4 or i == 9:
# For subtractive cases, e.g., 4 -> "IV" and 9 -> "IX"
s += roman[place] + roman[place * (i + 1)]
else:
if i >= 5:
s += roman[place * 5]
s += roman[place] * (i - 5)
else:
s += roman[place] * i
length -= 1
return s
# Example usage:
if __name__ == '__main__':
sol = Solution()
print(sol.intToRoman(3749)) # Output: "MMMDCCXLIX"
▎Problem A: Milya and Two Arrays
Contest: Codeforces Round #2059
Time Limit: 1 second per test
Memory Limit: 256 megabytes
▎Problem Denoscription
An array is called good if every element x that appears in the array appears at least twice. For example, the arrays:
• [1, 2, 1, 1, 2]
• [3, 3]
• [1, 2, 4, 1, 2, 4]
are good, while the arrays:
• [1]
• [1, 2, 1]
• [2, 3, 4, 4]
are not good.
Milya has two good arrays a and b of length n . She can rearrange the elements in array a in any way she wants. After that, she obtains an array c of length n , where:
Your task is to determine whether Milya can rearrange the elements in array a such that there are at least 3 distinct elements in array c .
▎Input Format
• The first line contains an integer t ( 1 ≤ t ≤ 1000 ) — the number of test cases.
• For each test case:
• The first line contains an integer n ( 3 ≤ n ≤ 50 ) — the length of arrays a and b .
• The second line contains n integers a₁, a₂, ..., aₙ ( 1 ≤ aᵢ ≤ 10⁹ ) — the elements of array a .
• The third line contains n integers b₁, b₂, ..., bₙ ( 1 ≤ bᵢ ≤ 10⁹ ) — the elements of array b .
▎Output Format
For each test case, output "YES" if it is possible to obtain at least 3 distinct elements in array c by rearranging array a ; otherwise, output "NO". You can output each letter in any case (for example, "YES", "Yes", "yes", etc.).
▎Example Input
▎Example Output
Contest: Codeforces Round #2059
Time Limit: 1 second per test
Memory Limit: 256 megabytes
▎Problem Denoscription
An array is called good if every element x that appears in the array appears at least twice. For example, the arrays:
• [1, 2, 1, 1, 2]
• [3, 3]
• [1, 2, 4, 1, 2, 4]
are good, while the arrays:
• [1]
• [1, 2, 1]
• [2, 3, 4, 4]
are not good.
Milya has two good arrays a and b of length n . She can rearrange the elements in array a in any way she wants. After that, she obtains an array c of length n , where:
cᵢ = aᵢ + bᵢ (1 ≤ i ≤ n)
Your task is to determine whether Milya can rearrange the elements in array a such that there are at least 3 distinct elements in array c .
▎Input Format
• The first line contains an integer t ( 1 ≤ t ≤ 1000 ) — the number of test cases.
• For each test case:
• The first line contains an integer n ( 3 ≤ n ≤ 50 ) — the length of arrays a and b .
• The second line contains n integers a₁, a₂, ..., aₙ ( 1 ≤ aᵢ ≤ 10⁹ ) — the elements of array a .
• The third line contains n integers b₁, b₂, ..., bₙ ( 1 ≤ bᵢ ≤ 10⁹ ) — the elements of array b .
▎Output Format
For each test case, output "YES" if it is possible to obtain at least 3 distinct elements in array c by rearranging array a ; otherwise, output "NO". You can output each letter in any case (for example, "YES", "Yes", "yes", etc.).
▎Example Input
5
4
1 2 1 2
1 2 1 2
6
1 2 3 3 2 1
1 1 1 1 1 1
3
1 1 1
1 1 1
6
1 52 52 3 1 3
59 4 3 59 3 4
4
100 1 100 1
2 2 2 2
▎Example Output
YES
YES
NO
YES
NO
Codeforces
Problem - A - Codeforces
Codeforces. Programming competitions and contests, programming community
Leetcode with dani
▎Problem A: Milya and Two Arrays Contest: Codeforces Round #2059 Time Limit: 1 second per test Memory Limit: 256 megabytes ▎Problem Denoscription An array is called good if every element x that appears in the array appears at least twice. For example…
t = int(input())
while t>0:
t-=1
lenght = int(input())
arr1 = list(map(int,input().split()))
arr2 = list(map(int,input().split()))
hash1 = set()
hash2 = set()
for i in range(len(arr1)):
hash1.add(arr1[i])
hash2.add(arr2[i])
if (len(hash2)<=1 and len(hash1) <=2 )or (len(hash1)<=1 and len(hash2) <=2 ):
print("NO")
else:
print("YES")
How to Set Up and Use Competitive Programming Tools for Codeforces
Many of you have asked how to use Codeforces efficiently for running and submitting code. It can be difficult to debug submissions when errors occur on random test cases without showing the input and output. Below is the method I use to make the process easier.
Step-by-Step Guide
1. Install Required Extensions
- Open Google Chrome and install the Competitive Companion extension.
- Install CPH Submit from the Chrome Web Store.
2. Set Up VS Code
- Open VS Code and install the Competitive Programming Helper extension.
3. Organizing Your Workspace
- Open VS Code and create a new folder, e.g.,
- You only need to create this folder once; after that, you can use it for all your problems without needing to create new folders repeatedly.
4. Using Competitive Companion
- Go to a Codeforces problem.
- Click the Competitive Companion extension in your browser.
- This will automatically send the problem statement and test cases to your VS Code environment.
5. Running and Submitting Code
- Write your solution in VS Code.
- Use the Competitive Programming Helper to run test cases locally.
- Submit the solution using the CPH Submit extension.
This setup makes running and debugging Codeforces problems much easier, especially when dealing with hidden test cases. I hope this helps!
https://news.1rj.ru/str/zethioprograming
Many of you have asked how to use Codeforces efficiently for running and submitting code. It can be difficult to debug submissions when errors occur on random test cases without showing the input and output. Below is the method I use to make the process easier.
Step-by-Step Guide
1. Install Required Extensions
- Open Google Chrome and install the Competitive Companion extension.
- Install CPH Submit from the Chrome Web Store.
2. Set Up VS Code
- Open VS Code and install the Competitive Programming Helper extension.
3. Organizing Your Workspace
- Open VS Code and create a new folder, e.g.,
Competitive Programming.- You only need to create this folder once; after that, you can use it for all your problems without needing to create new folders repeatedly.
4. Using Competitive Companion
- Go to a Codeforces problem.
- Click the Competitive Companion extension in your browser.
- This will automatically send the problem statement and test cases to your VS Code environment.
5. Running and Submitting Code
- Write your solution in VS Code.
- Use the Competitive Programming Helper to run test cases locally.
- Submit the solution using the CPH Submit extension.
This setup makes running and debugging Codeforces problems much easier, especially when dealing with hidden test cases. I hope this helps!
https://news.1rj.ru/str/zethioprograming
🙏6
Forwarded from Codeforces Official
Educational Codeforces Round 174
(rated for Div. 2) starts on the 18th of February at 14:35 UTC.
Please, join by the link https://codeforces.com/contests/2069
(rated for Div. 2) starts on the 18th of February at 14:35 UTC.
Please, join by the link https://codeforces.com/contests/2069
Codeforces
Educational Codeforces Round 174 (Rated for Div. 2) - Codeforces
Codeforces. Programming competitions and contests, programming community
🚀 Code Into the Future – Learn & Grow with Expert-Led Courses!
🌟 I see a lot of people talking about ALX and recommending it, so it might be worth checking out! Before feburary 24
for African student
🔥 ProDev Front-End Developer
📅 Duration: 8 Months | ⏳ 30 hrs/week | 🌍 Online
💡 Skills: TypeScript, TailwindCSS, Next.js, React Native, Figma
🔥 Front-End Web Development
📅 Duration: 8 Months | ⏳ 20 hrs/week | 🌍 Online
💡 Skills: HTML, CSS, JavaScript, GitHub, Figma
🔥 ProDev Back-End Developer
📅 Duration: 8 Months | ⏳ 30 hrs/week | 🌍 Online
💡 Skills: Django, Python, SQL, Git, GitHub
🔥 Back-End Web Development
📅 Duration: 8 Months | ⏳ 20 hrs/week | 🌍 Online
💡 Skills: Django, Python, SQL, Git, GitHub
🔥 AWS Cloud Computing
📅 Duration: 10 Months | ⏳ 30-40 hrs/week | 🌍 Online
💡 Skills: AWS Console, Linux Terminal
🔥 ALX Pathway Programme
📅 Duration: 8 Months
🎓 Exclusive access for High School graduates to global university partners & scholarships!
📌 Start your journey here:
🌟 I see a lot of people talking about ALX and recommending it, so it might be worth checking out! Before feburary 24
for African student
🔥 ProDev Front-End Developer
📅 Duration: 8 Months | ⏳ 30 hrs/week | 🌍 Online
💡 Skills: TypeScript, TailwindCSS, Next.js, React Native, Figma
🔥 Front-End Web Development
📅 Duration: 8 Months | ⏳ 20 hrs/week | 🌍 Online
💡 Skills: HTML, CSS, JavaScript, GitHub, Figma
🔥 ProDev Back-End Developer
📅 Duration: 8 Months | ⏳ 30 hrs/week | 🌍 Online
💡 Skills: Django, Python, SQL, Git, GitHub
🔥 Back-End Web Development
📅 Duration: 8 Months | ⏳ 20 hrs/week | 🌍 Online
💡 Skills: Django, Python, SQL, Git, GitHub
🔥 AWS Cloud Computing
📅 Duration: 10 Months | ⏳ 30-40 hrs/week | 🌍 Online
💡 Skills: AWS Console, Linux Terminal
🔥 ALX Pathway Programme
📅 Duration: 8 Months
🎓 Exclusive access for High School graduates to global university partners & scholarships!
📌 Start your journey here:
👍1
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
*Example 1:*
*Example 2:*
Approach:
To solve this problem, iterate through each number in the input array, extract its digits, and append them to the result array in the correct order. This can be achieved by converting each number to a string, splitting it into individual characters, and then converting those characters back to integers.
Python Solution:
Explanation:
1. Initialize an empty list
2. Iterate over each number
3. Convert the number to a string and split it into individual characters using
4. Convert each character back to an integer and extend the
5. After processing all numbers, return the
This approach ensures that the digits are added to the result list in the same order they appear in each number and maintains the order of numbers as they appear in the input list.
For more information and alternative solutions, you can refer to the [LeetCode problem discussion]
Problem Denoscription:
Given an array of positive integers
nums, return an array answer that consists of the digits of each integer in nums after separating them in the same order they appear in nums.*Example 1:*
Input: nums = [13, 25, 83, 77]
Output: [1, 3, 2, 5, 8, 3, 7, 7]
Explanation:
- The separation of 13 is [1, 3].
- The separation of 25 is [2, 5].
- The separation of 83 is [8, 3].
- The separation of 77 is [7, 7].
answer = [1, 3, 2, 5, 8, 3, 7, 7].
*Example 2:*
Input: nums = [7, 1, 3, 9]
Output: [7, 1, 3, 9]
Explanation: The separation of each integer in nums is itself.
answer = [7, 1, 3, 9].
Approach:
To solve this problem, iterate through each number in the input array, extract its digits, and append them to the result array in the correct order. This can be achieved by converting each number to a string, splitting it into individual characters, and then converting those characters back to integers.
Python Solution:
class Solution:
def separateDigits(self, nums: List[int]) -> List[int]:
result = []
for num in nums:
digits = list(str(num)) # Convert number to string and split into characters
result.extend(int(digit) for digit in digits) # Convert characters back to integers and add to result
return result
Explanation:
1. Initialize an empty list
result to store the separated digits.2. Iterate over each number
num in the input list nums.3. Convert the number to a string and split it into individual characters using
list(str(num)).4. Convert each character back to an integer and extend the
result list with these integers.5. After processing all numbers, return the
result list containing all the separated digits.This approach ensures that the digits are added to the result list in the same order they appear in each number and maintains the order of numbers as they appear in the input list.
For more information and alternative solutions, you can refer to the [LeetCode problem discussion]
LeetCode
Separate the Digits in an Array - LeetCode
Can you solve this real interview question? Separate the Digits in an Array - Given an array of positive integers nums, return an array answer that consists of the digits of each integer in nums after separating them in the same order they appear in nums.…
class Solution:
def separateDigits(self, nums: List[int]) -> List[int]:
return list(map(int,list(''.join(map(str,nums)))))
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