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
🌟 Day 9 Challenge: Count Number of Nice Subarrays 🌟

🔗 Problem Link: Count Number of Nice Subarrays Difficulty: Medium

📝 Problem Statement:
Given an array of integers nums and an integer k, a continuous subarray is called nice if it contains exactly k odd numbers. Return the number of nice subarrays.

Two Approaches to Solve the Problem

Approach 1: Sliding Window Technique

This approach uses a sliding window to count the number of subarrays with exactly k odd numbers.



class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
def atMostK(k):
count = 0
left = 0
for right in range(len(nums)):
if nums[right] % 2 == 1:
k -= 1
while k < 0:
if nums[left] % 2 == 1:
k += 1
left += 1
count += right - left + 1
return count

return atMostK(k) - atMostK(k - 1)


Explanation:

1. Function atMostK(k): This helper function counts the number of subarrays that contain at most k odd numbers. It uses a sliding window where left and right pointers define the current window.

2. Counting Subarrays: For each position of right, if the number is odd, we decrement k. If k becomes negative, we increment left until we have at most k odd numbers again. The number of valid subarrays ending at right is added to the count.

3. Final Calculation: The main function returns the difference between the counts of subarrays with at most k and k-1 odd numbers, which gives us exactly k.

Approach 2: Using Indices of Odd Numbers

This approach tracks the indices of odd numbers directly and counts the valid subarrays based on these indices.

class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
total = 0
count_odd = 0
l = 0
myset = []

for i in range(len(nums)):
if nums[i] % 2: # Check if the number is odd
myset.append(i) # Store the index of the odd number
count_odd += 1

if count_odd > k:
# If we have more than k odd numbers, we need to move the left pointer
if l:
l1 = (myset[l] - (myset[l - 1])) # Distance between two odd indices
r = i - myset[-2] # Distance from the second last odd index to current
total += l1 * r # Count subarrays formed
else:
r = i - myset[-2]
total += (myset[l] + 1) * r # Count subarrays formed when l is 0

l += 1 # Move the left pointer
count_odd -= 1 # Decrease the count of odd numbers

# Check for the last segment if count_odd >= k
if count_odd >= k:
if l:
l1 = (myset[l] - (myset[l - 1]))
r = (len(nums) - myset[-1])
total += l1 * r
else:
r = (len(nums) - myset[-1])
total += (myset[l] + 1) * r

return total


Explanation:

1. Initialization: Similar to the first approach, we initialize variables to track counts and indices.

2. Iterate through the array: For each element, check if it’s odd and update our list of indices (myset) and counts.

3. Adjusting for excess odds: When the count exceeds k, adjust the left pointer to maintain exactly k odds and calculate valid subarrays based on distances between stored indices.

4. Final Count: After processing, check for any remaining valid segments to add to the total.


Complexity Analysis for Both Approaches:

Time Complexity: O(n), where n is the length of the input array. Both approaches iterate through the array a single time.

Space Complexity: O(n) in the worst case for storing indices in Approach 2.

Example Usage:
Leetcode with dani
https://youtu.be/03ogf95osXw?si=qvW3WGO78Y9-G_yn
For those who didn't see the video, the speaker challenges the old idea that just knowing how to code will guarantee you a good job. With AI becoming more popular, the tech world is changing fast. Big companies like Google, Salesforce, Meta, and Amazon are now using advanced AI tools to do tasks that used to be done by human coders, and they can do them just as well as mid-level engineers. This shift is not only changing how companies hire but also leading to job cuts in the industry.

But the speaker argues that coding isn't going away. Instead, we need to think differently: we should combine our coding skills with new AI tools. He shares a simple five-step plan for developers who want to succeed in this new environment. This plan focuses on having a strong coding foundation, using AI to work more efficiently, understanding how AI works, applying these skills to real projects, and always learning as the field changes.

GPT's opinion : I believe that while AI can handle many routine tasks, the creative and problem-solving parts of coding are still really important. In my opinion, coding makes up about 80% of the development process, with AI helping out with the other 20%—making things easier and taking care of repetitive work. Embracing the combination of human creativity and AI technology is essential for success in the tech world moving forward.
👍3
🚀 Challenge for Aspiring Weightlifters! 🏋️‍♂️

Yaman, an aspiring weightlifter, is gearing up for his next tournament and needs your help! He has n barbell plates, each with a specific weight aᵢ and width bᵢ . Yaman's goal is to distribute these plates into two subsets: one for the left side of the barbell and one for the right.

His coach has defined a balancing function f(l, r) as follows:

f(l, r) = (| ∑(i ∈ l) bᵢ - ∑(i ∈ r) bᵢ )|

Yaman has to ensure that the absolute difference in widths between the two sides falls within a specified range during his training.

Your Task:

For each test case, determine the maximum total weight Yaman can lift while keeping the balancing function's value within the range [L, R]. If it's impossible to achieve this balance, you should return 0 .

Input Format:

• The first line contains the number of test cases t ( 1 ≤ t ≤ 10⁵ ).

• Each test case starts with two integers n (number of plates) and q (number of tests).

• The next line lists n integers representing the weights of the plates.

• The following line lists n integers representing the widths of the plates.

• The next q lines each contain two integers Lᵢ and Rᵢ , specifying the desired range for the balancing function.

Output Format:

For each test, output the maximum total weight Yaman can lift while maintaining the balancing function's value within the specified range. If it's not possible, output 0 .

Example:

Input:
1
5 4
5 2 3 2 5
1 4 9 12 20
1 2
7 7
99 100
3 3


Output:
17
12
0
14


Can you help Yaman achieve his training goals? Share your solutions and strategies! 💪

🔗 GotoCodeForce
👍2
Leetcode with dani
🚀 Challenge for Aspiring Weightlifters! 🏋️‍♂️ Yaman, an aspiring weightlifter, is gearing up for his next tournament and needs your help! He has n barbell plates, each with a specific weight aᵢ and width bᵢ . Yaman's goal is to distribute these plates…
in Short Yaman is training with a barbell that has plates of varying weights and widths. He needs to distribute these plates between the left and right sides of the barbell. The goal is to maximize the total weight lifted while ensuring that the difference in total widths between the two sides falls within a specified range [L, R]. For each test case, determine the maximum weight Yaman can lift under these conditions. If it's not possible to achieve the desired width balance, the result should be 0.
🌟 Day 11 Challenge: Find Pivot Index 🌟

🔗 Problem Link: 724. Find Pivot Index

📝 Problem Statement:
Given an array of integers nums, calculate the pivot index of this array.

The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.

If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.

Return the leftmost pivot index. If no such index exists, return -1.

---

🔍 Approach: Prefix Sum

We can use a prefix sum technique to efficiently check for the pivot index.

Steps to Solve:

1. Compute prefix sums: We maintain a prefix sum array p, where p[i] stores the sum of elements from index 0 to i-1.

2. Iterate through the array: For each index i, check if the left sum (p[i] - nums[i-1]) equals the right sum (p[-1] - p[i]).

3. Return the first valid index: If we find an index where both sums match, return it.

4. Return -1 if no pivot index is found.

---

📝 Code Implementation:

class Solution:
def pivotIndex(self, nums: List[int]) -> int:
# Step 1: Compute prefix sum
p = [0] # Prefix sum array initialized with 0
for i in range(len(nums)):
p.append(p[-1] + nums[i]) # Store cumulative sum

# Step 2: Iterate through the array and check pivot condition
for i in range(1, len(p)):
left_sum = p[i] - nums[i - 1] # Sum of elements to the left of index i-1
right_sum = p[-1] - p[i] # Sum of elements to the right of index i-1

if left_sum == right_sum:
return i - 1 # Return the pivot index

return -1 # If no pivot index is found


---

📝 Explanation of the Code:

1. Building Prefix Sum Array:

• We initialize p with [0] to store cumulative sums.

• Iterate through nums, appending the cumulative sum to p.

2. Finding Pivot Index:

• For each i, compute:

Left sum: p[i] - nums[i-1] (sum of elements before index i-1).

Right sum: p[-1] - p[i] (sum of elements after index i-1).

• If both sums are equal, return i-1.

3. Edge Case Handling:

• If no such index exists, return -1.

---

Complexity Analysis:

Time Complexity: O(N) (single pass for prefix sum + single pass for checking pivot index).

Space Complexity: O(N) (extra space for prefix sum array).
👍2
🌟 Day 11 Challenge: Walking Robot Simulation 🤖

🔗 Problem Link: 874. Walking Robot Simulation

Hey everyone! 👋 Today, we’re solving an interesting robot movement problem where the robot moves on an infinite grid while avoiding obstacles! 🚀

---

📝 Problem Statement:

A robot starts at (0,0) facing north and follows a series of commands:

-2: Turn left 90°

-1: Turn right 90°

1 ≤ k ≤ 9: Move forward k units

• If the robot hits an obstacle, it stops moving in that direction but continues executing the next command.

🛑 Goal: Find the maximum squared Euclidean distance the robot reaches from the origin (0,0).

💡 Key Notes:

• North → +Y

• East → +X

• South → -Y

• West → -X

---

🔍 Understanding with Examples

📌 Example 1:
Input: commands = [4,-1,3], obstacles = []
Output: 25
The robot moves to (3,4), and the max squared distance is 3² + 4² = 25.

📌 Example 2 (With Obstacles):
Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]]
Output: 65
The robot gets blocked at (2,4), then continues moving north to (1,8), reaching a max squared distance of 1² + 8² = 65.

---

🏗 Approach to Solve the Problem

1️⃣ Track directions efficiently:

• Use dx, dy arrays to manage the direction changes when turning left or right.

2️⃣ Use a set for obstacles for quick lookup (O(1) checks).

3️⃣ Loop through commands and update position accordingly:

• If moving forward → Check if the next step is an obstacle.

• If turning → Update direction accordingly.

---

💻 Code (Python)

class Solution:
def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:
# Step 1: Define movement directions (North, East, South, West)
directions = [(0,1), (1,0), (0,-1), (-1,0)]
x, y, max_dist, d = 0, 0, 0, 0 # Robot starts at (0,0), facing North

# Step 2: Convert obstacles list into a set for quick lookups
obstacle_set = set(map(tuple, obstacles))

# Step 3: Process each command
for command in commands:
if command == -2: # Turn left
d = (d - 1) % 4
elif command == -1: # Turn right
d = (d + 1) % 4
else: # Move forward k steps
for _ in range(command):
next_x, next_y = x + directions[d][0], y + directions[d][1]

# Stop moving if an obstacle is hit
if (next_x, next_y) in obstacle_set:
break

x, y = next_x, next_y # Update position
max_dist = max(max_dist, x*x + y*y) # Update max distance

return max_dist # Return max squared Euclidean distance


---

📝 Explanation of the Code:

1. Tracking Directions:

• We use an array directions = [(0,1), (1,0), (0,-1), (-1,0)] to handle North, East, South, and West movements.

• Turning left (-2) moves us backwards in the array, while turning right (-1) moves us forward.

2. Efficient Obstacle Lookup:

• We store obstacles in a set (O(1) lookup) instead of a list to quickly check if a position is blocked.

3. Processing Commands:

• For k steps forward, check if the next step is an obstacle:

If not blocked, update x, y.

If blocked, stop moving in that direction.

• Keep track of the maximum squared Euclidean distance reached.

---

Complexity Analysis:

Time Complexity: O(N + M), where N = len(commands), M = len(obstacles)

Space Complexity: O(M) (for storing obstacles in a set)
i added new books check it
2👍2
Codeforces (Div. 3)
A. Candies

Time limit per test: 1 second
Memory limit per test: 256 megabytes

Problem Statement

Recently, Vova found n candy wrappers. He remembers that he bought x candies during the first day, 2x candies during the second day, 4x candies during the third day, and so on.

On the k -th day, he bought 2⁽ᵏ⁻¹⁾ ⋅ x candies. However, Vova doesn't remember x or k , but he is sure that:

• x and k are positive integers

• k > 1

Vova will be satisfied if you find any positive integer x such that there exists some integer k > 1 where:

x + 2x + 4x + … + 2ᵏ⁻¹x = n


It is guaranteed that at least one solution exists.

Input

The first line contains one integer t (1 ≤ t ≤ 10⁴) — the number of test cases.

Each of the next t lines contains one integer n (3 ≤ n ≤ 10⁹) — the number of candy wrappers Vova found.

Output

For each test case, print one integer — any valid x such that there exists an integer k > 1 satisfying the given equation.

Examples

Input

7
3
6
7
21
28
999999999
999999984


Output

1
2
1
7
4
333333333
333333328


Explanation

• For n = 3 , one possible solution is x = 1, k = 2 since 1 ⋅ 1 + 2 ⋅ 1 = 3 .

• For n = 6 , one possible solution is x = 2, k = 2 since 1 ⋅ 2 + 2 ⋅ 2 = 6 .

• For n = 7 , one possible solution is x = 1, k = 3 since 1 ⋅ 1 + 2 ⋅ 1 + 4 ⋅ 1 = 7 .

---

Solution Code

t = int(input())
while t > 0:
t-=1
num = int(input())
k = 3
n = 4
while num % k:
k += n
n *= 2
print(num // k)


🔗 Problem link: Codeforces 1343A - Candies
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

• M = 1000

Example Test Cases

1. Input: int_to_roman(1994)
Output: "MCMXCIV"
Explanation: 1994 = 1000 (M) + 900 (CM) + 90 (XC) + 4 (IV).

2. Input: int_to_roman(58)
Output: "LVIII"
Explanation: 58 = 50 (L) + 5 (V) + 3 (III).

3. Input: int_to_roman(4)
Output: "IV"
Explanation: 4 is represented as IV.

4. Input: int_to_roman(9)
Output: "IX"
Explanation: 9 is represented as IX.

5. Input: int_to_roman(3999)
Output: "MMMCMXCIX"
Explanation: 3999 = 3000 (MMM) + 900 (CM) + 90 (XC) + 9 (IX).

Constraints

• Input integer num will be in the range [1, 3999].
Try it
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

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.

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:

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
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., 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